Skip to content

Commit

Permalink
Lax email validation
Browse files Browse the repository at this point in the history
  • Loading branch information
danschultzer committed Aug 24, 2019
1 parent 996f7c6 commit 3dc6aba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
7 changes: 4 additions & 3 deletions lib/pow/ecto/schema/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -241,16 +241,17 @@ defmodule Pow.Ecto.Schema.Changeset do
Config.get(config, :email_validator, &__MODULE__.validate_email/1)
end

@rfc_5332_regexp_no_ip ~r<\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z>
@naive_email_regexp ~r/^(?<user>[^\s]+)@(?<domain>[^\s]+\.[^\s]+)$/

@doc """
Validates an e-mail.
Complies to RFC 5332 spec without IP.
This is a naive implementation that only expects the format
`<username>@<domain>`. The domain requires a TLD.
"""
@spec validate_email(binary()) :: :ok | :error | {:error, any()}
def validate_email(email) do
case email =~ @rfc_5332_regexp_no_ip do
case email =~ @naive_email_regexp do
true -> :ok
false -> :error
end
Expand Down
19 changes: 15 additions & 4 deletions test/pow/ecto/schema/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,6 @@ defmodule Pow.Ecto.Schema.ChangesetTest do
refute changeset.valid?
assert changeset.errors[:email] == {"has invalid format", [validator: &Pow.Ecto.Schema.Changeset.validate_email/1]}

changeset = User.changeset(%User{}, Map.put(@valid_params, "email", ".wooly@example.com"))
refute changeset.valid?
assert changeset.errors[:email] == {"has invalid format", [validator: &Pow.Ecto.Schema.Changeset.validate_email/1]}

changeset = User.changeset(%User{}, @valid_params)
assert changeset.valid?
end
Expand Down Expand Up @@ -229,4 +225,19 @@ defmodule Pow.Ecto.Schema.ChangesetTest do
assert_received {:password_verify, "secret1234", "hash"}
end
end

test "validate_email/1" do
assert Changeset.validate_email(".wooly@example.com") == :ok
assert Changeset.validate_email("john.doe@example.com") == :ok
assert Changeset.validate_email("john.doe+spam@example.com") == :ok
assert Changeset.validate_email("john.doe@subdomain.example.com") == :ok
assert Changeset.validate_email("☞@example.com") == :ok
assert Changeset.validate_email("はな@example.com") == :ok

refute Changeset.validate_email("invalid") == :ok
refute Changeset.validate_email("john.doe@") == :ok
refute Changeset.validate_email("example.com") == :ok
refute Changeset.validate_email("@example.com") == :ok
refute Changeset.validate_email("john@example") == :ok
end
end

0 comments on commit 3dc6aba

Please sign in to comment.