Ruby on Rails Validation
Ruby on Rails (often just Rails) is a popular web application framework written in Ruby. One of its core features is validation, which ensures that data entered into a Rails application meets specific criteria before being saved to the database. Validations help maintain data integrity, enhance user experience, and prevent invalid or incomplete data from being processed.
Table of Content
What is Validation in Ruby on Rails?
Validation in Ruby on Rails is a mechanism to enforce rules on the data within your application's models. It ensures that data conforms to certain rules before it is saved to the database. This is crucial for maintaining the consistency and accuracy of the data your application handles.
- Data Integrity: Validation helps to ensure that the data entering the system adheres to specific criteria and constraints, preventing the storage of incorrect or incomplete data.
- User Feedback: It helps to provide meaningful error messages to users when they submit invalid data, improving user experience.
- Before Saving: Validations are performed before the data is saved to the database. If any validation fails, the data is not saved, and the object is returned with errors.
- Model-Level Validation: Validations are defined within model classes in Rails. When an object is created or updated, Rails runs these validations to check if the data meets the specified rules.
Built-in Validation Methods
Rails provides several built-in validation methods that you can use to validate your data. Let’s see some of the most common ones.
- 'presence: true': Ensures that a field is not empty.
- 'uniqueness: true': Ensures that a field's value is unique across the database.
- 'length: { minimum: x, maximum: y }': Validates the length of a field's value.
- 'numericality: true': Ensures that a field contains only numbers.
- 'format: { with: regex }': Validates that a field's value matches a specific pattern.
- 'inclusion: { in: range }': Validates that a field's value is included in a given set or range.
Implementing Validation Methods
Let's create a simple demo application to see these validations in action. We’ll build a basic application to manage users.
Step 1: Create a New Rails Application
Create a demo application using the below command.
rails new validation_demo cd validation_demo

Step 2: Generate a User Model
Run the following command to generate a 'User' model with a few fields.
rails generate model User name:string email:string age:integer gender:string password:string

Then, migrate the database,
rails db:migrate

Step 3: Add Validations to the User Model
Open the 'app/models/user.rb' file and add the following validations.
class User < ApplicationRecord
validates :name, presence: { message: "can't be blank" }
validates :email, presence: { message: "can't be blank" },
uniqueness: { message: "has already been taken" },
format: { with: /\A[\w\.-]+@[\w\.-]+\.[a-zA-Z]{2,}\z/, message: "is not a valid email address" }
validates :age, numericality: { greater_than_or_equal_to: 18, message: "must be at least 18" }
validates :gender, inclusion: { in: %w(Male Female Non-binary Other), message: "%{value} is not a valid gender" }
validates :password, length: { minimum: 6, maximum: 12, message: "must be between 6 and 12 characters" }
end
Here’s what each validation does:
- Name: Must be present (not empty).
- Email: Must be present, unique, and formatted as a valid email address using the regular expression.
- Age: Must be a number and at least 18 years old.
- Gender: Must be a value from available options.
- Password: Must be at least 6 characters long and a maximum of 12 characters.
Step 4: Create a Simple Form
Next, let’s create a form for users to sign up. Start by generating a 'UsersController'.
rails generate controller Users new create show

Then, in the 'app/controllers/users_controller.rb' file, add the following.
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to user_path(@user)
else
render :new
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name, :email, :age, :gender, :password)
end
end
Next, create a view for the 'new' action in 'app/views/users/new.html.erb'.
<h1>New User</h1>
<%= form_with model: @user, local: true do |form| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.text_field :email %>
</div>
<div class="field">
<%= form.label :age %>
<%= form.number_field :age %>
</div>
<div class="field">
<%= form.label :gender %>
<%= form.select :gender, options_for_select(['Male', 'Female', 'Non-binary', 'Other']) %>
</div>
<div class="field">
<%= form.label :password %>
<%= form.password_field :password %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Next, create a view for the 'new' action in 'app/views/users/show.html.erb'.
<h1>User Details</h1>
<p>
<strong>Name:</strong>
<%= @user.name %>
</p>
<p>
<strong>Email:</strong>
<%= @user.email %>
</p>
<p>
<strong>Age:</strong>
<%= @user.age %>
</p>
<p>
<strong>Gender:</strong>
<%= @user.gender %>
</p>
<p>
<strong>Password:</strong>
<%= @user.password %>
</p>
This page will be displayed after the successful submission of the form without breaking any validation.
Step 5: Setup Routes
Make changes in 'config/routes.rb' like this,
Rails.application.routes.draw do
resources :users, only: [:new, :create, :show]
end
Use the below command to execute the code:
rails server
Output
Each input will be checked according to the validation rules specified in the User model. If any input fails to meet the defined criteria, such as presence, format, or length, then the form will not be submitted. After successful submission, the user data will be visible on the next page. You can use a 'flash' message or JavaScript to display error messages.
Skipping Validations
Skipping validations in Ruby on Rails can be useful in certain scenarios, such as when you need to make a quick update to a record without enforcing all the validations. Here are some examples of how you can skip validations using the Rails console.
1. Skipping Validations with 'save(validate: false)'
You can skip validations when saving a record by passing 'validate: false' to the 'save' method. This tells Rails to save the record without running any validations.
Now, let's create a user in the Rails console.
rails console
Create an object 'user' with record details.
user = User.new(name:"john", email:"john@gmail.com", age:15, gender:"Male", password:"123")
Try to save it without skipping validations.
user.save
It will give 'false' since the age is less than 18.
Now, save the record while skipping validations.
user.save(validate:false)
See the below output for better understanding:

2. Skipping Validations with 'update_attribute'
The 'update_attribute' method skips validations for a single attribute and saves the record directly.
Open the rails console and create an object 'user'.
user = User.find_by(email: "johndoe@gmail.com")
Try to update the age with validation. It will give 'false'.
user.update(age: 12)
Skip validations and update the age.
user.update_attribute(:age, 12)
See the below output for better understanding:

Conclusion
Validation in Ruby on Rails is a powerful tool that helps you ensure data integrity in your applications. With the built-in validation methods, you can easily enforce rules on your data before it gets saved to the database. In this article, we covered the basics of validations, including how to create a simple application with a form that uses various validation methods. With this knowledge, you're ready to start adding validations to your Rails applications.
Related Articles:
- Create a User SignUp Form With Email Using Ruby on Rails
- Routes in ruby on rails
- Features of Ruby on Rails
- How to Build an API With Ruby on Rails?