Skip to content

Instantly share code, notes, and snippets.

@mgamini
Last active March 27, 2023 17:42
Show Gist options
  • Save mgamini/4f3a8bc55bdcc96be2c6 to your computer and use it in GitHub Desktop.
Save mgamini/4f3a8bc55bdcc96be2c6 to your computer and use it in GitHub Desktop.
Elixir Email Validation
defmodule EmailValidator do
# ensure that the email looks valid
def validate_email(email) when is_binary(email) do
case Regex.run(~r/^[\w.!#$%&’*+\-\/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i, email) do
nil ->
{:error, "Invalid email"}
[email] ->
try do
Regex.run(~r/(\w+)@([\w.]+)/, email) |> validate_email
rescue
_ -> {:error, "Invalid email"}
end
end
end
# check the email against a list of accepted domains, then make check if it is unique
def validate_email([email, username, host]) do
case host in Config.accepted_domains do
true ->
case find_by_email(email) do
nil -> :ok
_account -> :account
end
_ ->
{:error, "Not an accepted domain."}
end
end
end
@nallwhy
Copy link

nallwhy commented Feb 22, 2018

~r/^[A-Za-z0-9._%+-+']+@[A-Za-z0-9.-]+\.[A-Za-z]+$/
no more {2,4}

@DarckBlezzer
Copy link

DarckBlezzer commented Jan 24, 2020

I recomended this regex

~r/^[\w.!#$%&’*+\-\/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i

Check this link:
http://blog.gerv.net/2011/05/html5_email_address_regexp/

@mgamini
Copy link
Author

mgamini commented Jan 27, 2020

Updated. Thank you!

@alg
Copy link

alg commented Apr 21, 2020

You are including both lowercase and uppercase ranges and then adding case-insensitivity flag. One of them is unnecessary.

@TylerPachal
Copy link

~r/^[A-Za-z0-9._%+-+']+@[A-Za-z0-9.-]+\.[A-Za-z]+$/ no more {2,4}

I think you want to escape your dash between the + characters in the first "section" of the regex:

~r/^[A-Za-z0-9._%+\-+']+@[A-Za-z0-9.-]+\.[A-Za-z]+$/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment