tvieira
tvieira

Reputation: 1915

Rails validation confirm true is not case sensitive?

In my user.rb model, I have a email_confirm field, so that users insert twice and validate the emails without typos

attr_accessor :email_confirmation
validates :email, confirmation: true, on: :create
validates :email_confirmation, presence: true, allow_nil: true

But what happens is, if I insert an email with a capital letter, I get an validation error "don't match". How do I confirm emails without case sensitive?

I'm using devise

Upvotes: 3

Views: 1331

Answers (2)

Matouš Borák
Matouš Borák

Reputation: 15944

I would use a custom validator:

class User < ActiveRecord::Base

  attr_accessor :email_confirmation

  validates :email, presence: true
  validate  :check_email_confirmation, if: :email_changed?

  private

  def check_email_confirmation
    if email.casecmp(email_confirmation.to_s).nonzero?
      errors.add(:email, "Emails don't match")
    end
  end

end

casecmp is a case-insensitive string compare method. It does not work properly for fully-accented UTF-8 characters comparison but you don't need that in emails.

With this approach you don't have to change the input attributes in any way before validation. Also, I updated the validations so that email is a required attribute and that the confirmation check is done only when email changes.

Upvotes: 1

Anthony E
Anthony E

Reputation: 11235

For email validation, use a regex matcher:

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

The i flag at the end of the regex sets case insensitivity. This validation also handles presence, since nil or a blank string would fail the above validation.

I recommend using Rubular for testing regexes: http://rubular.com/

EDIT

You can preprocess the attribute in a before_validation block:

before_validation :downcase_email

def downcase_email
  email_confirmation.try(:downcase!)
  email.try(:downcase!)
end

try is to prevent calling downcase! if email is nil.

Upvotes: 1

Related Questions