Last active
October 15, 2024 10:32
-
-
Save woylie/ea06d7edfcfb8e834771a17b5afd2800 to your computer and use it in GitHub Desktop.
Email validation according to RFC 5322 with Elixir and gen_smtp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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