Ruby on Rails: Validation in Models

August 1, 2007

Validating incoming data to make sure data is according to business logic rules is important and is easy to do in Rails. The best place to get more information is Official Rails Documentation site ( but if you want a general overview, proceed further.

As a data gatekeeper, Model class can be a perfect place to keep all your data validations. That way whatever way you create/modify data (programmatically or user interface) the validations work.

Basically we could write validations in 3 passes,

Pass 1: Use Rails inbuilt simple validation rules

a) Field should not be empty
Rails Method: validates_presence_of
Example: validates_presence_of :user_name, :password

b) Field should Numerical
Rails Method: validates_numericality_of
Example: validates_numericality_of :value

c) Field should not be Unique
Rails Method:validates_uniqueness_of
Example: validates_uniqueness_of :user_name

d) Field Need to be of size X
Rails Method: validates_length_of
Example: validates_length_of :state_code, :is=>2

e) Field size Need to be of between X to Y
Rails Method: validates_length_of
Example: validates_uniqueness_of :user_name

Pass 2 :  Write Regular Expression to do validation 
Requirement: Field Need to be in Certain Format like Email or DOB

Rails Method: validates_format_of

Example: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create  

(Tip : For all the above validations you could add :message => “Your customized message if validatation fails”  to customize Error Messages)

Pass 3 : Custom Validations

Finally, for any other custom validations like say if product_price should be more than $100 or salary_requested less than 100K, define a protected method “validate” inside your model. Then use errors object to add any messages if validation fails like   errors.add (:your_field, “your message”).

example from Book “Rails Solutions” By Justin Williams

def validate

  errors.add(:price, “should be a positive value”) if price.nil?|| price < 0.01



10 Responses to “Ruby on Rails: Validation in Models”

  1. Jason Says:

    Thanks for the tip! Very useful.

  2. Hong Says:

    You provided the duplicate sample in “Rails Method: validates_length_of”

  3. Jacob Lyles Says:

    There’s an error in Pass 1:

    c) Field should not be Unique <– Field should be Unique
    Rails Method:validates_uniqueness_of
    Example: validates_uniqueness_of :user_name

  4. Joe Says:

    That custom validation code is basically the same as what it in the book Agile Web Development with Rails on page 66. Weird that two different books would have basically the same sample code for that :)

  5. if anyone is wondering about how to get the error message to show in the view here it is:

    I spent some time trying to find the answer to this one

  6. I had to take out the surrounding symbols and equals sign as it didnt show…

    error_messages_for ‘model_name_goes_here’

  7. tez Says:

    I have in my migration file next raws:
    t.integer “min”, :limit => 3, :default => 50, :null => false
    When I put validation like:
    validates_length_of :min,:maximum=>3
    and put in this field 2 symbols I get strange validation issue:Min is too long (maximum is 3 characters)

    Please advise what can be the reason,I need to restrict input more the 3 symbols

  8. Chassidy Says:

    After application the hair is simply dried, either naturally
    or using a drier. Since these goods are made from plant extracts, seed oils
    and hair only twice in a week. A well groomed woman will look to her hair and makeup first and a poll of 3,000 females across the UK revealed that about 44% feel attractive if they are having a good hair day, this compares to 16% who felt
    pleased with their appearance if good teeth gave them that winning

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: