2008-03-31 20:05:48 -04:00
|
|
|
module ActiveModel
|
|
|
|
module Validations
|
2009-12-22 18:36:51 -05:00
|
|
|
class ExclusionValidator < EachValidator
|
2009-12-22 19:08:27 -05:00
|
|
|
def check_validity!
|
|
|
|
raise ArgumentError, "An object with the method include? is required must be supplied as the " <<
|
|
|
|
":in option of the configuration hash" unless options[:in].respond_to?(:include?)
|
|
|
|
end
|
|
|
|
|
2009-12-22 18:36:51 -05:00
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
return unless options[:in].include?(value)
|
|
|
|
record.errors.add(attribute, :exclusion, :default => options[:message], :value => value)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2008-03-31 20:05:48 -04:00
|
|
|
module ClassMethods
|
|
|
|
# Validates that the value of the specified attribute is not in a particular enumerable object.
|
|
|
|
#
|
|
|
|
# class Person < ActiveRecord::Base
|
|
|
|
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
|
|
|
|
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
|
2009-03-19 19:28:59 -04:00
|
|
|
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension {{value}} is not allowed"
|
2008-03-31 20:05:48 -04:00
|
|
|
# end
|
|
|
|
#
|
|
|
|
# Configuration options:
|
2009-03-19 19:28:59 -04:00
|
|
|
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
|
|
|
|
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
|
|
|
|
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
|
|
|
|
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
|
2008-05-02 09:45:23 -04:00
|
|
|
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
|
|
|
|
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
|
2008-03-31 20:05:48 -04:00
|
|
|
# method, proc or string should return or evaluate to a true or false value.
|
2008-05-02 09:45:23 -04:00
|
|
|
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
|
|
|
|
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
|
2008-03-31 20:05:48 -04:00
|
|
|
# method, proc or string should return or evaluate to a true or false value.
|
|
|
|
def validates_exclusion_of(*attr_names)
|
2010-01-07 12:44:35 -05:00
|
|
|
validates_with ExclusionValidator, _merge_attributes(attr_names)
|
2008-03-31 20:05:48 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2009-06-08 21:32:08 -04:00
|
|
|
end
|