Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve email validation regexp #4341

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion core/lib/spree/core/validators/email.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ module Spree
#
class EmailValidator < ActiveModel::EachValidator
EMAIL_REGEXP = URI::MailTo::EMAIL_REGEXP
EMAIL_DOMAIN_REGEXP = /\.[a-z]+/i

def validate_each(record, attribute, value)
unless EMAIL_REGEXP.match? value
unless valid_email?(value)
record.errors.add(attribute, :invalid, { value: value }.merge!(options))
end
end

def valid_email?(value)
EMAIL_REGEXP.match?(value) && EMAIL_DOMAIN_REGEXP.match?(value)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK the key issue is that URI::MailTo::EMAIL_REGEXP doesn't validate that addresses end with a domain suffix. Perhaps you can maintain the protection of the original regex and just add an additional validation that the address includes a domain suffix?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer using a single step for the validation, it's just a matter to find a good and battle testes regexp 🙂

end
end
end
3 changes: 2 additions & 1 deletion core/spec/lib/spree/core/validators/email_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ class Tester
'invalidemailemail.com',
'@[email protected]',
'invalid@[email protected]',
'invalid.email@@email.com'
'invalid.email@@email.com',
'invalid.email@gmail'
]
}

Expand Down