Skip to content

Instantly share code, notes, and snippets.

@woylie
Last active October 15, 2024 10:32
Show Gist options
  • Save woylie/ea06d7edfcfb8e834771a17b5afd2800 to your computer and use it in GitHub Desktop.
Save woylie/ea06d7edfcfb8e834771a17b5afd2800 to your computer and use it in GitHub Desktop.
Email validation according to RFC 5322 with Elixir and gen_smtp
import Ecto.Changeset
@spec validate_email(Ecto.Changeset.t(), atom) :: Ecto.Changeset.t()
def validate_email(changeset, field) when is_atom(field) do
changeset
|> validate_length(field, max: 160)
|> validate_change(field, &validate_email_rfc5322/2)
end
defp validate_email_rfc5322(field, email) do
charlist = String.to_charlist(email)
with {:ok, tokens, _} <- :smtp_rfc5322_scan.string(charlist),
{:ok, _} <- :smtp_rfc5322_parse.parse(tokens) do
[]
else
_ -> [{field, {"is invalid", validation: :format}}]
end
rescue
_ -> [{field, {"is invalid", validation: :format}}]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment