You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Email validation will be done mainly by sending a validation link. However it can be useful to filter out valid email formats from the start, just in case someone accidentally types in an invalid email format.
Don't use a regular expression for email address validation. It's a trap. There are way more valid email address formats than you'll think of. However! The mail gem (it's required by ActionMailer, so you have it) will parse email addresses — with a proper parser — for you:
This will throw a Mail::Field::ParseError if it's a non-compliant email address. (We're not getting into things like doing an MX address lookup or anything.)
If you want the good ol' Rails validator experience, you can make app/models/concerns/email_validatable.rb:
require'mail'moduleEmailValidatableextendActiveSupport::ConcernclassEmailValidator < ActiveModel::EachValidatordefvalidate_each(record,attribute,value)begina=Mail::Address.new(value)rescueMail::Field::ParseErrorrecord.errors[attribute] << (options[:message] || "is not an email")endendendend
As Iwo Dziechciarow's comment below mentions, this passes anything that's a valid "To:" address through. So something like Foo Bar <[email protected]> is valid. This might be a problem for you, it might not; it really is a valid address, after all.
As Björn Weinbrenne notes below, there are way more valid RFC2822 addresses than you may expect (I'm quite sure all of the addresses listed there are compliant, and may receive mail depending system configurations) — this is why I don't recommend trying a regex, but using a compliant parser.
If you really care whether you can send email to an address then your best bet — by far — is to actually send a message with a verification link.
The text was updated successfully, but these errors were encountered:
Email validation will be done mainly by sending a validation link. However it can be useful to filter out valid email formats from the start, just in case someone accidentally types in an invalid email format.
Browsing on stackoverflow, I found a mention of the valid_email2 gem which could help some:
The text was updated successfully, but these errors were encountered: