Last active
June 25, 2020 03:04
-
-
Save aesmail/a38e605e568579c2b48ff400a9dff32f to your computer and use it in GitHub Desktop.
Email format validation helper text
This file contains 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
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/@/, "[email protected]") 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