diff options
Diffstat (limited to 'activemodel/lib/active_model')
-rw-r--r-- | activemodel/lib/active_model/errors.rb | 13 | ||||
-rw-r--r-- | activemodel/lib/active_model/locale/en.yml | 1 | ||||
-rw-r--r-- | activemodel/lib/active_model/validations/absence.rb | 31 |
3 files changed, 45 insertions, 0 deletions
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index 963e52bff3..b713e99e25 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -328,6 +328,19 @@ module ActiveModel end end + # Will add an error message to each of the attributes in +attributes+ that + # is present (using Object#present?). + # + # person.errors.add_on_present(:name) + # person.errors.messages + # # => { :name => ["must be blank"] } + def add_on_present(attributes, options = {}) + Array(attributes).flatten.each do |attribute| + value = @base.send(:read_attribute_for_validation, attribute) + add(attribute, :not_blank, options) if value.present? + end + end + # Returns +true+ if an error on the attribute with the given message is # present, +false+ otherwise. +message+ is treated the same as for +add+. # diff --git a/activemodel/lib/active_model/locale/en.yml b/activemodel/lib/active_model/locale/en.yml index d17848c861..8ea34b84f5 100644 --- a/activemodel/lib/active_model/locale/en.yml +++ b/activemodel/lib/active_model/locale/en.yml @@ -13,6 +13,7 @@ en: accepted: "must be accepted" empty: "can't be empty" blank: "can't be blank" + not_blank: "must be blank" too_long: "is too long (maximum is %{count} characters)" too_short: "is too short (minimum is %{count} characters)" wrong_length: "is the wrong length (should be %{count} characters)" diff --git a/activemodel/lib/active_model/validations/absence.rb b/activemodel/lib/active_model/validations/absence.rb new file mode 100644 index 0000000000..6790554907 --- /dev/null +++ b/activemodel/lib/active_model/validations/absence.rb @@ -0,0 +1,31 @@ +module ActiveModel + module Validations + # == Active Model Absence Validator + class AbsenceValidator < EachValidator #:nodoc: + def validate(record) + record.errors.add_on_present(attributes, options) + end + end + + module HelperMethods + # Validates that the specified attributes are blank (as defined by + # Object#blank?). Happens by default on save. + # + # class Person < ActiveRecord::Base + # validates_absence_of :first_name + # end + # + # The first_name attribute must be in the object and it must be blank. + # + # Configuration options: + # * <tt>:message</tt> - A custom error message (default is: "must be blank"). + # + # There is also a list of default options supported by every validator: + # +:if+, +:unless+, +:on+ and +:strict+. + # See <tt>ActiveModel::Validation#validates</tt> for more information + def validates_absence_of(*attr_names) + validates_with AbsenceValidator, _merge_attributes(attr_names) + end + end + end +end |