VOOZH about

URL: https://www.geeksforgeeks.org/ruby/ruby-on-rails-validation/

⇱ Ruby on Rails Validation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Ruby on Rails Validation

Last Updated : 23 Jul, 2025

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.

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.

  1. 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.
  2. User Feedback: It helps to provide meaningful error messages to users when they submit invalid data, improving user experience.
  3. 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.
  4. 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.

  1. 'presence: true': Ensures that a field is not empty.
  2. 'uniqueness: true': Ensures that a field's value is unique across the database.
  3. 'length: { minimum: x, maximum: y }': Validates the length of a field's value.
  4. 'numericality: true': Ensures that a field contains only numbers.
  5. 'format: { with: regex }': Validates that a field's value matches a specific pattern.
  6. '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

πŸ‘ Create a Rails app
Create a Rails App

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

πŸ‘ User Model
User Model

Then, migrate the database,

rails db:migrate

πŸ‘ Database Migration
Database Migration

Step 3: Add Validations to the User Model

Open the 'app/models/user.rb' file and add the following validations.

Here’s what each validation does:

  1. Name: Must be present (not empty).
  2. Email: Must be present, unique, and formatted as a valid email address using the regular expression.
  3. Age: Must be a number and at least 18 years old.
  4. Gender: Must be a value from available options.
  5. 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

πŸ‘ User Controller
User Controller

Then, in the 'app/controllers/users_controller.rb' file, add the following.

Next, create a view for the 'new' action in 'app/views/users/new.html.erb'.

Next, create a view for the 'new' action in 'app/views/users/show.html.erb'.

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,

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:

πŸ‘ Skip Validation Using Save(validate:false)
Skip Validation Using Save(validate:false)

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:

πŸ‘ Skip Validation Using update_attribute
Skip Validation Using update_attribute

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:

Comment
Article Tags:
Article Tags: