Skip to content

Instantly share code, notes, and snippets.

@samullen
Created December 27, 2011 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samullen/1524999 to your computer and use it in GitHub Desktop.
Save samullen/1524999 to your computer and use it in GitHub Desktop.
Validator class for validating the absence of value in a field if other conditions are met.
class AbsenceValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless value
if options.empty? # don't know why you would want this
record.errors[attribute] << "must be blank"
elsif options[:all] && options[:all].all? {|sym| record.read_attribute(sym)}
record.errors[attribute] << "must be blank if the following attributes are defined: #{options[:all].join(', ')}"
elsif options[:any] && options[:any].any? {|sym| record.read_attribute(sym)}
record.errors[attribute] << "must be blank if any of the following attributes are defined: #{options[:any].join(", ")}"
else
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment