2020-01-26 20:36:50 +00:00
|
|
|
|
defmodule Mobilizon.Web.Email.Checker do
|
2018-11-15 16:35:47 +00:00
|
|
|
|
@moduledoc """
|
2019-09-22 14:26:23 +00:00
|
|
|
|
Provides a function to test emails against a "not so bad" regex.
|
2018-11-15 16:35:47 +00:00
|
|
|
|
"""
|
|
|
|
|
|
2020-01-28 19:15:59 +00:00
|
|
|
|
@email_regex ~r/^[\w.!#$%&’*+\-\/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i
|
2018-11-15 16:35:47 +00:00
|
|
|
|
|
|
|
|
|
@doc """
|
2019-09-22 14:26:23 +00:00
|
|
|
|
Returns whether the email is valid.
|
2018-11-15 16:35:47 +00:00
|
|
|
|
"""
|
2019-09-22 14:26:23 +00:00
|
|
|
|
@spec valid?(String.t()) :: boolean
|
|
|
|
|
def valid?(email), do: email =~ @email_regex
|
2019-12-20 12:04:34 +00:00
|
|
|
|
|
2021-10-05 13:29:06 +00:00
|
|
|
|
@spec validate_changeset(Ecto.Changeset.t()) :: Ecto.Changeset.t()
|
|
|
|
|
def validate_changeset(%Ecto.Changeset{} = changeset) do
|
2019-12-20 12:04:34 +00:00
|
|
|
|
changeset = Ecto.Changeset.validate_length(changeset, :email, min: 3, max: 250)
|
|
|
|
|
|
2021-10-05 13:29:06 +00:00
|
|
|
|
case Ecto.Changeset.fetch_change(changeset, :email) do
|
2019-12-20 12:04:34 +00:00
|
|
|
|
{:ok, email} ->
|
|
|
|
|
if valid?(email),
|
|
|
|
|
do: changeset,
|
|
|
|
|
else: Ecto.Changeset.add_error(changeset, :email, "Email doesn't fit required format")
|
|
|
|
|
|
|
|
|
|
:error ->
|
|
|
|
|
changeset
|
|
|
|
|
end
|
|
|
|
|
end
|
2018-11-15 16:35:47 +00:00
|
|
|
|
end
|