Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

Email validation in Ruby on Rails?

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

[email protected]
[email protected]

still are valid. What am I missing?

Upvotes: 94

Views: 97780

Answers (14)

Joshua Hunter
Joshua Hunter

Reputation: 4458

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

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

warning - this considers a@b to be a valid email address

Upvotes: 276

Cyzanfar
Cyzanfar

Reputation: 7136

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.

Upvotes: 14

Martin T.
Martin T.

Reputation: 3222

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 }

Upvotes: 38

Dayana Alonso
Dayana Alonso

Reputation: 39

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 :)

Upvotes: 1

gayavat
gayavat

Reputation: 19398

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

Upvotes: 3

A H K
A H K

Reputation: 1750

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

Upvotes: 3

Adriano Tadao
Adriano Tadao

Reputation: 986

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

Upvotes: 5

Nate
Nate

Reputation: 4739

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.

Upvotes: 32

Martin T.
Martin T.

Reputation: 3222

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

Upvotes: 4

Jack Barry
Jack Barry

Reputation: 310

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!

Upvotes: 8

tongueroo
tongueroo

Reputation: 1197

@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.

Upvotes: 9

jithya
jithya

Reputation: 428

try this.

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

Upvotes: 3

thaleshcv
thaleshcv

Reputation: 752

Try validates_email_format_of gem.

Upvotes: 5

Vipin CP
Vipin CP

Reputation: 3797

You can try this

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

Upvotes: 4

Related Questions