Simple Reference to Rails built-in validations

Validations are a way to get a Rails project to show error messages when illegal values are entered into fields. This document provides a simple reference to Rails built-in validators, all of which are accessible through the validates method. The examples are based on the Student model, which can be created with the following commands:

rails generate scaffold Student name:string gpa:float sid:integer email:string
rake db:migrate

The model (class) name is Student. Note that replacing scaffold with model in the above command will create only the model code for the application.

Listed below are some common examples of validations that are added within the body of the Model class. Open the app/models/student.rb file, and add validations for the attributes.

Validating that a value is present

The :presence option requires that the specified attribute actually has a value.

class Student < ActiveRecord::Base
validates :email, :presence => true
end

Validating that a value is unique

The :uniqueness option validates whether the value of the specified attribute is unique across the system

class Student < ActiveRecord::Base
validates :email, :uniqueness => true
end

Validating Length or Size

Use the :length option to validate the length of size of a field entry

Validating that field is a numeric value

Use the :numericality option to validate that an attribute value is a numeric value

validates :sid, :uniqueness => true, :numericality=> true, :length => {:within => 8..10},

Validating range of field