/Ruby on Rails 7.0

class ActiveModel::EachValidator


EachValidator is a validator which iterates through the attributes given in the options hash invoking the validate_each method passing in the record, attribute and value.

All Active Model validations are built on top of this validator.



Public Class Methods

new(options) Show source
# File activemodel/lib/active_model/validator.rb, line 138
def initialize(options)
  @attributes = Array(options.delete(:attributes))
  raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?

Returns a new validator instance. All options will be available via the options reader, however the :attributes option will be removed and instead be made available through the attributes reader.

Calls superclass method ActiveModel::Validator::new

Public Instance Methods

check_validity!() Show source
# File activemodel/lib/active_model/validator.rb, line 166
def check_validity!

Hook method that gets called by the initializer allowing verification that the arguments supplied are valid. You could for example raise an ArgumentError when invalid options are supplied.

validate(record) Show source
# File activemodel/lib/active_model/validator.rb, line 148
def validate(record)
  attributes.each do |attribute|
    value = record.read_attribute_for_validation(attribute)
    next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
    value = prepare_value_for_validation(value, record, attribute)
    validate_each(record, attribute, value)

Performs validation on the supplied record. By default this will call validate_each to determine validity therefore subclasses should override validate_each with validation logic.

validate_each(record, attribute, value) Show source
# File activemodel/lib/active_model/validator.rb, line 159
def validate_each(record, attribute, value)
  raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"

Override this method in subclasses with the validation logic, adding errors to the records errors array where necessary.

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.