How to write custom validation in Ruby on Rails
Fortunately writing custom validation is really easy in Rails. In your model create a method called validate and in there you can place your custom validation checks. For example:
def validate
errors.add_to_base "If you are attaching a file you must enter a label for it" if !attachment.blank? and attachment_label.blank?
end
This custom validation does a simple check to see if the user has attempted to upload an attachment and if they have, ensure that they have entered a label for it.
The errors.add_to_base part means the error message will be output along with any other error messages using
<%= error_messages_for :object %>
If you require your custom validation to be reused across your more than one ActiveRecord model you should take a look at Peter Marklund's article that looks at all the different ways this can be achieved.
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
4 comments made
Yuz, good stuff
thanx i was really getting anoyed by now. thanx again
You also can add a message error by an especific attribute, like this:
errors.add :name, ‘Taigo isnt a name’ if self.name == ‘Taigo’
Thanks. Exactly what I needed. Found off Google. It was nice and concise.
Got something to say?