Validates each attribute against a block.
class Person < ActiveRecord::Base validates_each :first_name, :last_name do |record, attr, value| record.errors.add attr, 'starts with z.' if value[0] == ?z end end
Options:
- on - Specifies when this validation is active (default is :save, other options :create, :update)
- allow_nil - Skip validation if attribute is nil.
- allow_blank - Skip validation if attribute is blank.
- if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.
- unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.
Source Code
# File active_record/validations.rb, line 383 def validates_each(*attrs) options = attrs.extract_options!.symbolize_keys attrs = attrs.flatten # Declare the validation. send(validation_method(options[:on] || :save)) do |record| # Don't validate when there is an :if condition and that condition is false or there is an :unless condition and that condition is true unless (options[:if] && !evaluate_condition(options[:if], record)) || (options[:unless] && evaluate_condition(options[:unless], record)) attrs.each do |attr| value = record.send(attr) next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) yield record, attr, value end end end end
<code/>and<pre/>for code samples.