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.

Comments left...

  • Yuz, good stuff

    Pimp at 11 Mar 08 at 11:42

  • thanx i was really getting anoyed by now. thanx again

    Usman at 27 Jul 08 at 23:46

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

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

    Tiago Albineli Motta at 31 Jul 08 at 23:05

  • Thanks. Exactly what I needed. Found off Google. It was nice and concise.

    Thanks at 18 Sep 08 at 20:41

  • <= error_messages_for :object ><= error_messages_for :object ><= error_messages_for :object ><= error_messages_for :object ><= error_messages_for :object ><= error_messages_for :object >

    <%= error_messages_for :object %> at 25 Feb 09 at 06:12

  • Yuz, good stuff

    Pimp commented on 11 Mar 08 at 11:42 at 25 Feb 09 at 06:15

Got something to say?