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
rails 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-
Specifies that student ID value (sid) is between 8 and 10 characters
validates :sid, uniqueness: true, length: {within: 8..10}
-
Specifies that minimum size of attribute is 5
validates :email, uniqueness: true, length: {minimum: 5}
-
Specifies that maximum size of attribute is 30
validates :email, uniqueness: true, length: {maximum: 30}
-
Specifies that exact size is 8
validates :sid, uniqueness: true, length: {is: 8}
-
Specifies the error message if attribute is of wrong size
validates :sid, uniqueness: true, length: {within: 8..10, wrong_length: "Value should be between 8 and 10 characters"}
Validating that field is a numeric value
Use the numericality option to validate that an attribute value is a numeric valuevalidates :sid, uniqueness: true, numericality: true, length: {within: 8..10},
Validating range of field
-
Use the inclusion option to validate that an attribute value is within a specified range.
validates :gpa, numericality: true, inclusion: {in: 0..4, message: "Value should be between 0 and 4"}
-
We can also validate that an attribute takes specific values. Consider the following example
for gender field that can only be "male" or "female":
validates :gender, inclusion: %w(male female)
-
Use the :exclusion option to validate that an attribute value is NOT within a specified range.
validates :age, numericality: true, exclusion: {in: 0..18, message=> "Age should be larger than 18"}