Email validation in Ruby on Rails?

Ruby on-RailsEmail

Ruby on-Rails Problem Overview


I am doing email validation in Rails with:

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

Also, I do HTML5 validation in the frontend but email addresses like

..abc@gmail.com
.abc@gmail.com

still are valid. What am I missing?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

I use the constant built into URI in the standard ruby library

validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 

Solution 2 - Ruby on-Rails

Update: I just found the valid_email2 gem which looks pretty great.

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:

require 'mail'
a = Mail::Address.new('[email protected]')

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
end

and then in your model, you can:

include EmailValidatable
validates :email, email: true

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.

If you do want just the address portion of it:

a = Mail::Address.new('Foo Bar <[email protected]>')
a.address
=> "[email protected]"

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.

Solution 3 - Ruby on-Rails

If you use the Devise gem already in your app, it might be opportune to use

email =~ Devise.email_regexp

...which also means different places of the app use the same validation.

If you want to add it as an attribute validator to your ActiveRecord model:

validates :email, format: { with: Devise.email_regexp }

Solution 4 - Ruby on-Rails

Here is the new rails way to do email validation:

validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }

Refer to the Rails validations doc.

Solution 5 - Ruby on-Rails

@Nate Thank you so much for putting this answer together. I did not realize email validation had so many nuances until I looked at your code snippet.

I noticed that the current mail gem: mail-2.6.5 doesn't throw an error for an email of "abc". Examples:

>> a = Mail::Address.new('abc')
=> #<Mail::Address:70343701196060 Address: |abc| >
>> a.address # this is weird
=> "abc"
>> a = Mail::Address.new('"Jon Doe" <[email protected]>')
=> #<Mail::Address:70343691638900 Address: |Jon Doe <[email protected]>| >
>> a.address
=> "[email protected]"
>> a.display_name
=> "Jon Doe"
>> Mail::Address.new('"Jon Doe <jon')
Mail::Field::ParseError: Mail::AddressList can not parse |"Jon Doe <jon|
Reason was: Only able to parse up to "Jon Doe <jon
  from (irb):3:in `new'
  from (irb):3
>>

It does throw Mail::Field::ParseError errors for "Jon Doe <jon which is great. I believe will check for the simple "abc pattern" also.

In app/models/concerns/pretty_email_validatable.rb:

require 'mail'

module PrettyEmailValidatable
  extend ActiveSupport::Concern

  class PrettyEmailValidator < 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

      # regexp from http://guides.rubyonrails.org/active_record_validations.html
      value = a.address
      unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
        record.errors[attribute] << (options[:message] || "is not an email")
      end
    end

  end
end

and then in your model, you can:

include PrettyEmailValidatable
validates :pretty_email, email: true

So I use the above for "pretty email" validation and the https://github.com/balexand/email_validator for standard email validation.

Solution 6 - Ruby on-Rails

If anybody else is very TDD focused: I wanted something that I could write tests against and improve upon later if needed, without tying the tests to another model.

Building off of Nate and tongueroo's code (Thanks Nate and tongueroo!), this was done in Rails 5, Ruby 2.4.1. Here's what I threw into app/validators/email_validator.rb:

require 'mail'

class EmailValidator < ActiveModel::EachValidator
  def add_error(record, attribute)
    record.errors.add(attribute, (options[:message] || "is not a valid email address"))
  end

  def validate_each(record, attribute, value)
    begin
      a = Mail::Address.new(value)
    rescue Mail::Field::ParseError
      add_error(record, attribute)
    end

    # regexp from http://guides.rubyonrails.org/active_record_validations.html
    value = a.address unless a.nil?
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      add_error(record, attribute)
    end
  end
end

And this is by no means comprehensive, but here's what I threw into spec/validators/email_validator_spec.rb:

require 'rails_helper'

RSpec.describe EmailValidator do
  subject do
    Class.new do
      include ActiveModel::Validations
      attr_accessor :email
      validates :email, email: true
    end.new
  end

  context 'when the email address is valid' do
    let(:email) { Faker::Internet.email }

    it 'allows the input' do
      subject.email = email
      expect(subject).to be_valid
    end
  end

  context 'when the email address is invalid' do
    let(:invalid_message) { 'is not a valid email address' }

    it 'invalidates the input' do
      subject.email = 'not_valid@'
      expect(subject).not_to be_valid
    end

    it 'alerts the consumer' do
      subject.email = 'notvalid'
      subject.valid?
      expect(subject.errors[:email]).to include(invalid_message)
    end
  end
end

Hope it helps!

Solution 7 - Ruby on-Rails

Solution 8 - Ruby on-Rails

You can try this

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i

Solution 9 - Ruby on-Rails

The simple answer is: Don't use a regexp. There are too many edge cases and false negatives and false positives. Check for an @ sign and send a mail to the address to validate it:

https://www.youtube.com/watch?v=xxX81WmXjPg

Solution 10 - Ruby on-Rails

Is better to follow Rails documentation:

https://guides.rubyonrails.org/active_record_validations.html#custom-validators

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end
 
class Person < ApplicationRecord
  validates :email, presence: true, email: true
end

Solution 11 - Ruby on-Rails

try this.

validates_format_of  :email, :with => /^[\+A-Z0-9\._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i

Solution 12 - Ruby on-Rails

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
!("[email protected]" =~ VALID_EMAIL_REGEX).nil?

Solution 13 - Ruby on-Rails

Please, be aware that for now email_validator gem does not have complex validation rules, but only:

/[^\s]@[^\s]/

https://github.com/balexand/email_validator/blob/master/lib/email_validator.rb#L13

Argumentation is in https://medium.com/hackernoon/the-100-correct-way-to-validate-email-addresses-7c4818f24643

Solution 14 - Ruby on-Rails

I had the same issue, and it was fixed with a simple one-line gem

gem 'validates_email_format_of'

in my model I added

validates :email, email_format: { message: 'Invalid email format' }

I hope this helps any newbie's like myself :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaseeb AhmadView Question on Stackoverflow
Solution 1 - Ruby on-RailsJoshua HunterView Answer on Stackoverflow
Solution 2 - Ruby on-RailsNateView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMartin T.View Answer on Stackoverflow
Solution 4 - Ruby on-RailsCyzanfarView Answer on Stackoverflow
Solution 5 - Ruby on-RailstonguerooView Answer on Stackoverflow
Solution 6 - Ruby on-RailsJack BarryView Answer on Stackoverflow
Solution 7 - Ruby on-RailsthaleshcvView Answer on Stackoverflow
Solution 8 - Ruby on-Railsvipin cpView Answer on Stackoverflow
Solution 9 - Ruby on-RailsMartin T.View Answer on Stackoverflow
Solution 10 - Ruby on-RailsAdriano TadaoView Answer on Stackoverflow
Solution 11 - Ruby on-RailsjithyaView Answer on Stackoverflow
Solution 12 - Ruby on-RailsA H KView Answer on Stackoverflow
Solution 13 - Ruby on-RailsgayavatView Answer on Stackoverflow
Solution 14 - Ruby on-RailsDayana AlonsoView Answer on Stackoverflow