Custom validation for a model

Ruby on Rails Add comments

Maybe this is spelled out somewhere else, but I struggled to find a way to create my own validation methods for my models. While the standard, built-in validation methods cover a lot of ground, there are always things that have to be done by hand. To the rescue comes validates_each.

In my case, I needed to validate that a certain field was either nil or matched a regular expression. Normally, you would use validates_format_of, but it did not seem to support allow_nil as an option.

To get this custom validation, I used the following:

Overriding validates_each in your model class makes it possible to create any sort of crazy validation that could be necessary. It might not be as pretty or small as the validates_such_and_such, but it’s nice to know the power is there.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in