Customizing Rails validation error messages

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.

Comments

  1. 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. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

eight + = 17