-
Notifications
You must be signed in to change notification settings - Fork 3
Description
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:
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
require 'mail' a = Mail::Address.new('foo@example.com')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' module EmailValidatable extend ActiveSupport::Concern class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) begin a = Mail::Address.new(value) rescue Mail::Field::ParseError record.errors[attribute] << (options[:message] || "is not an email") end end end endand then in your model, you can:
include EmailValidatable validates :email, email: trueAs Iwo Dziechciarow's comment below mentions, this passes anything that's a valid "To:" address through. So something like
Foo Bar <foo.bar@example.com>
is valid. This might be a problem for you, it might not; it really is a valid address, after all.If you do want just the address portion of it:
a = Mail::Address.new('Foo Bar <foobar@example.com>') a.address => "foobar@example.com"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.