Skip to content

Categories:

Customizing validation errors

From my code snippets repo, found this snippet from here – it’s another way of adding your own error messages (or overriding the default ones Rails throws back).

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

Posted in Tutorials. Tagged with .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.