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.The :presence option requires that the specified attribute actually has a value.
class Student < ActiveRecord::Base
validates :email, :presence => true
end
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
validates :sid, :uniqueness => true, :length => {:within => 8..10}
validates :email, :uniqueness => true, :length => {:minimum => 5}
validates :email, :uniqueness => true, :length => {:maximum => 30}
validates :sid, :uniqueness => true, :length => {:is => 8}
validates :sid, :uniqueness => true, :length => {:within => 8..10, :wrong_length=>"Value should be between 8 and 10 characters"}
validates :sid, :uniqueness => true, :numericality=> true, :length => {:within => 8..10},
validates :gpa, :numericality=> true, :inclusion => {:in => 0..4, :message => "Value should be between 0 and 4"}
validates :gender, :inclusion => %w(male female)
validates :age, :numericality=> true, :exclusion => {:in => 0..18, :message=> "Age should be larger than 18"}