debianize-mobilizon/lib/web/email/checker.ex

29 lines
853 B
Elixir
Raw Normal View History

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