mercredi 2 août 2017

Rails understand regex differently then rubular

I wanted to do a simple regex-based email validation:

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

Which is mentioned in rails documentation. I have checked it in rubular and everythings works fine, but in rails, emails with dot in local address fails validation for some reason (john.doe@example.com). What's weird is that it accepts any other non-whitespace characters (e.g &^%#!*() excluding @ of course).

  validates :email,      presence: true, length: { maximum: 64 },
                         uniqueness: { case_sensitive: false }, email: true

And failing test:

  test 'should validate email with special characters in local address' do
    @user.email = 'john.doe@domain.com'
    assert @user.valid?
  end

Any idea what could be the reason for that weird behaviour?

Aucun commentaire:

Enregistrer un commentaire