Custom Validations in Rails

Ruby on Rails comes bundled with several validators for its models. They’re used for ensuring that the data structure of the application matches the business logic of the application. There are several built-in validators that can be used to make sure that certain properties about the model are true before they are saved—and it’s easy to create custom validations in Rails.

Defining a validation is straightforward enough. Here’s an example of a validator that can check multiple attributes for errors:

class CustomCheckValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, parameters)
    if invalid(attribute, parameters)
      record.errors[attribute] << 'attribute is invalid.'

I prefer to create a new directory for custom validators—app/validators. That new directory then needs to be added into the Rails pipeline by adding the following line to the application’s config:

config.autoload_paths += %W["#{config.root}/app/validators/"]

Once the validator has been included in the pipeline, it can be used in the model in the same that the default Rails are:

validates :first_attribute, :second_attribute, custom_check: "a parameter"

Validations are a powerful tool to make sure that the application’s data doesn’t become out of sync with the business logic. More information on them can be found in the official Ruby on Rails guide.