Home > OS >  rails - add a custom validator per attribute in model
rails - add a custom validator per attribute in model

Time:10-07

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: NameValidator validates :age, with: AgeValidator

How can I achieve this?

thanks

CodePudding user response:

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

class Model < ActiveRecord
  validates :hard_validator_for_name


  private

  def hard_validator_for_name
     if self.name != 'VALID NAME'
       errors.add(:name, "name not valid")
     end
  end
end

CodePudding user response:

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

class Person < ApplicationRecord
  validates :email, presence: true, email: true
end

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s] )@((?:[-a-z0-9] \.) [a-z]{2,})\z/i
      record.errors.add attribute, (options[:message] || "is not an email")
    end
  end
end
  • Related