Lucian Tarna
Lucian Tarna

Reputation: 1827

Email with nonexistent domain name fails regex validation

I have the following validation on my user model:

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email,
    presence: true,
    format: { with: VALID_EMAIL_REGEX }

It works fine for emails except 1 email. I need this email to be valid. The test that fails is the following:

  it 'should accept a domain with more than 4 letters', focus: true do
    user.email = '[email protected]'
    expect(user.valid?).to be(true)
  end

This test should pass. Any ideas?(I am open to changing the regex completely for email validation)

These are all the validators on the User model on the email field:

#<EmailValidator:0x000000075b04d0
  @attributes=[:email],
  @options={:if=>#<Proc:0x000000075c5a10@/usr/local/rvm/gems/ruby-2.2.3@2parale/gems/devise_token_auth-0.1.37/app/models/devise_token_auth/concerns/user.rb:30>}>,
 #<ActiveRecord::Validations::PresenceValidator:0x00000007414338 @attributes=[:email], @options={}>,
 #<ActiveModel::Validations::FormatValidator:0x0000000740ef28 @attributes=[:email], @options={:with=>/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i}>,
 #<ActiveModel::Validations::LengthValidator:0x0000000740de98 @attributes=[:email], @options={:minimum=>6, :maximum=>100}>,
 #<ActiveRecord::Validations::UniquenessValidator:0x0000000740ccf0

Upvotes: 1

Views: 105

Answers (2)

David Stump
David Stump

Reputation: 492

This seems to be an issue where the devise_auth_token gem is overriding the default Devise email validations (https://github.com/lynndylanhurley/devise_token_auth/issues/314) causing issues for some folks. Unfortunately it does not appear that there is a nice way to tell the gem which updated format/validator you would like to use. This leaves you with three non-ideal options:

  1. Find another gem with less obtrusive behavior
  2. Monkey patch the class in question (EmailValidator)
  3. Fork the gem with the updates/changes you need and submit a PR

Sorry there doesn't seem to be a nice/easy way to fix this :(

Cheers.

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 98881

Why don't you use python-email-validator ?

Install:

pip install email_validator

Sample usage:

from email_validator import validate_email, EmailNotValidError

email = "[email protected]"

try:
    v = validate_email(email) # validate and get info
    email = v["email"] # replace with normalized form
except EmailNotValidError as e:
    # email is not valid, exception message is human-readable
    print(str(e))

Upvotes: 0

Related Questions