Skip to content

Instantly share code, notes, and snippets.

@aesmail
Last active June 25, 2020 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aesmail/a38e605e568579c2b48ff400a9dff32f to your computer and use it in GitHub Desktop.
Save aesmail/a38e605e568579c2b48ff400a9dff32f to your computer and use it in GitHub Desktop.
Email format validation helper text
defmodule MyApp.Blog.Author do
use Ecto.Schema
import Ecto.Changeset
schema "authors" do
field :name, :string
field :email, :string
# ...
end
def changeset(author, attrs) do
author
|> cast(attrs, [:email, :name, :supe_author])
|> validate_required([:email, :name])
|> validate_email_format()
|> validate_acceptable_email_providers()
end
defp validate_email_format(changeset) do
email = get_field(changeset, :email)
case Regex.run(~r/@/, "abdullah.esmail@gmail.com") do
nil -> add_error(changeset, :email, "Enter a valid email address")
_ -> changeset
end
end
defp validate_acceptable_email_providers(changeset) do
email = get_field(changeset, :email)
case String.ends_with?(email, ["@gmail.com", "@hotmail.com"]) do
true -> changeset
false -> add_error(changeset, :email, "You must use either a gmail or a hotmail account")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment