diff --git a/lib/valid_email2/address.rb b/lib/valid_email2/address.rb index c28c3d6..656b93d 100644 --- a/lib/valid_email2/address.rb +++ b/lib/valid_email2/address.rb @@ -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 @@ -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 diff --git a/spec/valid_email2_spec.rb b/spec/valid_email2_spec.rb index 4c45277..5bcbd1e 100644 --- a/spec/valid_email2_spec.rb +++ b/spec/valid_email2_spec.rb @@ -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 @@ -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