I have a model in which I have to validate specific attributes with a Validator. Because this validations are complex and long I'd like to specify in which attribute I want the different Validators to work.

pseudo code:validates :name, with: NameValidatorvalidates :age, with: AgeValidator

How can I achieve this?

thanks

2

Best Answer


You can define per-attribute custom validation classes like this:

class Person < ApplicationRecordvalidates :email, presence: true, email: trueendclass EmailValidator < ActiveModel::EachValidatordef validate_each(record, attribute, value)unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/irecord.errors.add attribute, (options[:message] || "is not an email")endendend

You can use custom validators (https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations) or use the validate method:

class Model < ActiveRecordvalidate :hard_validator_for_nameprivatedef hard_validator_for_nameif self.name != 'VALID NAME'errors.add(:name, "name not valid")endendend