Skip to content

Commit

Permalink
Validate that domains only includes allowed characters. Fixes #88
Browse files Browse the repository at this point in the history
  • Loading branch information
micke committed Oct 26, 2017
1 parent 778c37c commit c21da3d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/valid_email2/address.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ module ValidEmail2
class Address
attr_accessor :address

ALLOWED_DOMAIN_CHARACTERS_REGEX = /\A[a-z0-9\-.]+\z/i

def initialize(address)
@parse_error = false
@raw_address = address
Expand All @@ -22,8 +24,14 @@ def valid?

if address.domain && address.address == @raw_address
domain = address.domain
# Valid address needs to have a dot in the domain but not start with a dot
!!domain.match(/\./) && !domain.match(/\.{2,}/) && !domain.match(/^\./)

domain.match(ALLOWED_DOMAIN_CHARACTERS_REGEX) &&
# Domain needs to have at least one dot
domain.match(/\./) &&
# Domain may not have two consecutive dots
!domain.match(/\.{2,}/) &&
# Domain may not start with a dot
!domain.match(/^\./)
else
false
end
Expand Down
12 changes: 12 additions & 0 deletions spec/valid_email2_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ class BackwardsCompatibleUser < TestModel
describe "basic validation" do
subject(:user) { TestUser.new(email: "") }

it "should not be valid email is valid" do
user = TestUser.new(email: "foo@bar123.com")
expect(user.valid?).to be_truthy
end

it "should be valid when email is empty" do
expect(user.valid?).to be_truthy
end
Expand All @@ -33,6 +38,13 @@ class BackwardsCompatibleUser < TestModel
expect(user.valid?).to be_falsey
end

it "should be invalid when domain includes invalid characters" do
%w(+ _ !).each do |invalid_character|
user = TestUser.new(email: "foo@google#{invalid_character}yahoo.com")
expect(user.valid?).to be_falsey
end
end

it "should be invalid when email is malformed" do
user = TestUser.new(email: "foo@bar")
expect(user.valid?).to be_falsey
Expand Down

0 comments on commit c21da3d

Please sign in to comment.