Rails Validation

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well. Using built-in validation DSL, you can do several kinds of validations.

When an Active Record model class fails a validation, it is considered an error. Each Active Record model class maintains a collection of errors, which display appropriate error information to the users when validation error occurs.

Rails built-in Validation Methods

MethodDescription
validates_acceptance_ofThis validation is done by the user to accept a terms of service agreement by checking in a check box
validates_associatedValidates whether associated objects are all valid themselves. Work with any kind of association.
validates_confirmation_ofIt validates whether a user has entered matching information like password or email in second entry field.
validates_eachValidates each attribute against a block.
validates_exclusion_ofValidates that an attribute is not in a particular enumerable object.
validates_format_ofValidates value of an attribute using a regular expression to insure it is of correct format.
validates_inclusion_ofValidates whether value of an attribute is available in a particular enumerable object.
validates_length_ofValidates that length of an attribute matches length restrictions specified.
validates_numericality_ofValidates whether an attribute is numeric.
validates_presence_ofValidates that attribute is not blank.
validates_size_ofThis is an alias for validates_length_of
validates_uniqueness_ofValidates that an attribute is unique in the database.

Skipping Validations

The following Rails methods skip validations and save the object to the database regardless of its validity. They should be used with caution.

  • decrement!
  • decrement_counter
  • increment!
  • increment_counter
  • toggle!
  • touch
  • update_all
  • update_attribute

valid? and invalid?

Before saving an Active Record object, a validation is done by Rails. If any error is produced, object is not saved.

The valid? triggers your validations, returns true if no errors are found and false otherwise.

Example:

class Person < ApplicationRecord  

??validates :name, presence: true  

end  

?  

Person.create(name: "John Cena").valid? # => true  

Person.create(name: nil).valid? # => false

The invalid? is simply the reverse of valid?. It triggers your validations, returns true if invalid and false otherwise.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *