Creating Custom Validators in Rails
When building a Ruby on Rails application, you may need to implement custom validation rules for your models. Rails provides a wide range of built-in validators, but there might be instances where you need to create your own custom validators to suit your application’s specific requirements.
Understanding Validators in Rails
Validators are used in Rails to validate the data before saving it to the database. They ensure that the data meets certain conditions, such as presence, uniqueness, format, or custom business rules. Rails provides a variety of built-in validators, including presence, length, numericality, uniqueness, and more. These built-in validators cover most of the commonly required validation scenarios.
When to Create Custom Validators
While the built-in validators are robust, there may be occasions when they don’t fully address your application’s specific validation needs. In such cases, creating custom validators gives you the flexibility to define your own rules and conditions.
Creating a Custom Validator
The process of creating a custom validator in Rails is straightforward and follows a simple pattern:
- Create a new class that inherits from the
ActiveModel::EachValidator
base class. - Override the
validate_each
method, which receives the model object, the attribute being validated, and the value of that attribute. - Implement your custom validation logic inside the
validate_each
method. - Register your custom validator in the desired model using the
validates
method.
An Example Custom Validator
Let’s say we want to create a custom validator to ensure that a username doesn’t contain any profanity. Here’s an example of how we could implement this:
class ProfanityValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
profanity_list = ['bad_word_1', 'bad_word_2', 'bad_word_3']
if value&.split(' ')&.any? { |word| profanity_list.include?(word.downcase) }
record.errors.add(attribute, :profanity, message: "contains profanity")
end
end
end
In this example, we define a ProfanityValidator
class that inherits from ActiveModel::EachValidator
. In the validate_each
method, we check if the username contains any profanity by comparing it with our list of prohibited words. If a profanity is found, we add an error to the model’s errors collection using the add
method to notify the user.
Using the Custom Validator
After creating the custom validator, we can use it in any model by invoking the validates
method and passing the name of the attribute along with the custom validator:
class User < ApplicationRecord
validates :username, profanity: true
end
In this example, we apply the profanity
validator to the username
attribute in the User
model. Whenever a user tries to save a record with a username containing profanity, the model won’t be considered valid, and Rails will add an error to the username
attribute.
Conclusion
Creating custom validators in Rails allows you to implement specific validation rules tailored to your application’s requirements. By following the simple steps outlined above, you can easily define your own validators, enhancing the data integrity and improving the overall user experience of your Ruby on Rails application.
Leave a Reply