Ruby on Rails Q & A

 

How to create custom validators in Rails?

In Rails, while there are several built-in validators for common tasks, there are situations where you’ll need custom validation logic. Creating custom validators in Rails is both straightforward and flexible.

 

  1. Custom Validator Class:

The most structured way to create a custom validator is by defining a new validator class. This class should inherit from `ActiveModel::Validator`.

 


```ruby

class MyCustomValidator < ActiveModel::Validator

  def validate(record)

    unless record.attribute_meets_condition?

      record.errors[:attribute_name] << "Error message."

    end

  end

end

```

 

You can then use this validator in your model:

 


```ruby

class MyModel < ApplicationRecord

  validates_with MyCustomValidator

end

```

 

  1. Inline Custom Validators:

For simpler validation logic, Rails allows you to define validations directly in the model using the `validate` method:

 

```ruby

class MyModel < ApplicationRecord

  validate :my_custom_validation_method




  def my_custom_validation_method

    errors.add(:attribute_name, "Error message.") unless attribute_meets_condition?

  end

end

```

 

  1. Custom Validator Modules:

If you want to reuse a validation logic across multiple models, you can create custom validators as modules:

 

```ruby

module MyValidator

  extend ActiveSupport::Concern




  included do

    validate :my_custom_validation_method

  end




  def my_custom_validation_method

    errors.add(:attribute_name, "Error message.") unless attribute_meets_condition?

  end

end




class MyModel < ApplicationRecord

  include MyValidator

end

```

 

  1. Error Messages:

When adding errors in custom validators, you can also utilize Rails’ I18n features for internationalization of error messages. This ensures your application remains flexible for multiple locales.

 

Rails provides versatile tools for creating custom validation logic. Whether you choose to implement a dedicated validator class, an inline method, or a reusable module, you have the power to ensure your data integrity with ease and maintainability.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.