logo{ :from => Delhi, :about => everything }


Customizing Rails validation error messages

Posted in rails, ruby on rails, software by manik on the November 22nd, 2005


Rails Version information: activerecord-1.12.1, rails-0.14.1

I have a form, where the user enters a name, “johndoe”. I already have a user “johndoe”, and i want user name to be unique.
The default error message that validate_uniqueness_of returns is “Name is already taken”
But I want “Name johndoe is not available”.

Here is my user model, user.rb file, with the custom message.

class User < ActiveRecord::Base
  attr_accessor :password_confirmation, :mail_confirmation    

  before_validation_on_create 'self.class.validates_uniqueness_of :name, :message=>"#{self.name} is not available"'
  before_validation_on_create 'self.class.validates_uniqueness_of :mail, :message=>"#{self.mail} is already used by some other user"'

  def validate_on_create
    errors.add_on_blank %w( name password mail )
    errors.add_on_boundary_breaking('name', 5..12) if errors.on('name').nil?
    errors.add_on_boundary_breaking('password', 6..12) if errors.on('password').nil?
    errors.add('mail_confirmation', "and mail do not match.") unless mail_confirmation == mail
    errors.add('password_confirmation', "and Password do not match.") unless password_confirmation == password
  end

end

The callbacks before_validation_on_create, enclose the method to call in single quotes ’self.class …..’ , thereby asking Rails to evaluate self.class and self.name at the time of execution, at runtime.
Since validate_uniqueness_of is a Class method, we have to call it by self.class.validates_uniqueness_of,
And we overwrite the default error message, with our custom message.

Please refer ActiveRecord::Validations,
ActiveRecord::Validations::ClassMethods
and ActiveRecord::Callbacks in Rails api docs for more details.

Tags: , , , , ,

`

4 Responses to 'Customizing Rails validation error messages'

Subscribe to comments with RSS or TrackBack to 'Customizing Rails validation error messages'.

  1. Daniel said,

    on December 19th, 2005 at 9:32 pm

    Thanks for this - I’m currently working on a lot of validation with the ‘make it sooo pretty and easy to use for the user’ point of view in mind - so this helps! Much appreciated.

  2. Kevin Ready said,

    on March 8th, 2006 at 3:01 am

    Thanks for the tip. This works very well!

    Regards,

    Kevin Ready

  3. abhilash said,

    on February 26th, 2007 at 5:01 pm

    How to change the core Rails validation error messages using plugins?
    Or do u know any site that give me answer in brief ?
    Pls give in detail.


  4. on March 14th, 2007 at 10:35 pm

    Interesting. Thanks.

Leave a Reply