Davide Targa website

Programming, web development and open source

Case Insensitive Validation in Rails 3

The default uniqueness validation (using sexy validations) in Rails 3 is case sensitive. This is not always a good thing.

For example if you wrote the following class, with the following validation:

1
2
3
4
Class User < ActiveRecord::Base
  validates :username, :presence => true, :uniqueness => true
  ...
end

these usernames will pass the validation and will be stored in the database:

1
foo, Foo, fOo, fOO, ...

To avoid this problem you should make a change to the previous model in order to make the uniqueness validation case insensitive. To achieve this you have to pass an hash of parameters to the uniqueness validator. The new code may look like this:

1
2
3
4
Class User < ActiveRecord::Base
  validates :username, :presence => true, :uniqueness => {:case_sensitive => false}
  ...
end

Hope this helps :)

Comments