Rails 3. Validating email uniqueness and case sensitive fails

Viewed 25112

I am developing an app in Rails 3 and upon signup I need the user to enter their email address and I need it to be unique and case sensitive. I.e. no one should be able to sign up with myEmail@yahoo.com when MyEmail@yahoo.com already exists in the database.

This is my code and it crashes the app:

validates :email, :presence => true, :uniqueness => true, :case_sensitive => true,
                      :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}

What is wrong with it?

5 Answers

You can use a callback in your model like "before_validation" on email attribute to make it lowercased like this:

  before_validation { self.email = email.downcase }

This will make the email input lowercased, after that try uniqueness validation without case sensitive:

validates :email, uniqueness: true

For more info about callbacks: here is ruby guide https://guides.rubyonrails.org/active_record_callbacks.html

Related