Skip to content

How to write custom validation in Ruby on Rails

Posted on 16 July 2006

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.

View the snippets archive ››

3 comments made

Pimp commented on 11 Mar 08 at 11:42

Yuz, good stuff

Usman commented on 27 Jul 08 at 23:46

thanx i was really getting anoyed by now. thanx again

Tiago Albineli Motta commented on 31 Jul 08 at 23:05

You also can add a message error by an especific attribute, like this:

errors.add :name, ‘Taigo isnt a name’ if self.name == ‘Taigo’

Got something to say?

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