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:

validates_each :some_attribute do | record, attr, value |
if value && value =~ /my_regex/
record.errors.add attr, “must be either empty or blah blah…”
end
end

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.

2 Responses to “Custom validation for a model”

  1. paulreitz Says:

    I’m relatively new to rails, but I ran into a similar problem where I had to validate an email only if “contact by email” was selected. Just thought I’d pass on what I found :) so here is the solution:

    validates_format_of :email,
    :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
    :message => “Invalid email”,
    :if => Proc.new {|u| u.contact_method == 0}

    notice the :if at the end. Anyways, hopes this helps people avoid the hours of searching that I just went through :D

  2. arun mg Says:

    how to make custom validation on one string should contain 1st letter alphabet then second one numeric 1 then any characters length should be within 4 to 40

Leave a Reply

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