Ruby On Rails Validation

Learn how to use Ruby on Rails validation with an example to quickly ensure data integrity.

Ruby On Rails Validation

Validation is an important part of any application, and Ruby on Rails provides several built-in solutions to validate data. The most common way to validate data is to use the ActiveModel::Validations module. This module provides several methods to validate data before it is saved to the database.

The first type of validation is the presence validation. This type of validation is used to ensure that a value is present before saving the data. This type of validation is useful when saving data to the database and ensuring that all required fields are filled in. For example, if we have a model called Person that has a first_name and last_name field, we can use the presence validation to make sure that both of these fields are filled in before the data is saved.


class Person < ActiveRecord::Base
  validates :first_name, :last_name, presence: true
end

The next type of validation is the format validation. This type of validation is used to ensure that a value is in the correct format before saving the data. This type of validation is useful when we need to make sure that a value is in a specific format before saving it. For example, if we have a model called EmailAddress that has an email_address field, we can use the format validation to make sure that the email_address is in the correct format before it is saved.


class EmailAddress < ActiveRecord::Base
  validates :email_address, format: { with: /A([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})z/i, on: :create }
end

The last type of validation is the inclusion validation. This type of validation is used to ensure that a value is included in a predefined list of values before saving the data. This type of validation is useful when we need to make sure that a value is in a predefined list before saving it. For example, if we have a model called Gender that has a gender field, we can use the inclusion validation to make sure that the gender is either male or female before it is saved.


class Gender < ActiveRecord::Base
  validates :gender, inclusion: { in: %w(male female) }
end

These are just some of the types of validations that can be used in Ruby on Rails. There are many more validations available, and they can be used to ensure that data is valid before it is saved to the database.

Answers (0)