Module: ActiveModel::Validations::ClassMethods

### Home Classes Methods

### In Files

- lib/active_model/validations.rb
- lib/active_model/validations/validates.rb
- lib/active_model/validations/with.rb

### Methods

- #_validates_default_keys
- #attribute_method?
- #inherited
- #validate
- #validates
- #validates!
- #validates_each
- #validates_with
- #validators
- #validators_on

### Class/Module Index

Quicksearch

- ActiveModel
- ActiveModel::AttributeMethods
- ActiveModel::AttributeMethods::ClassMethods
- ActiveModel::AttributeMethods::ClassMethods::AttributeMethodMatcher
- ActiveModel::BlockValidator
- ActiveModel::Callbacks
- ActiveModel::Conversion
- ActiveModel::Dirty
- ActiveModel::EachValidator
- ActiveModel::Errors
- ActiveModel::Lint
- ActiveModel::Lint::Tests
- ActiveModel::MassAssignmentSecurity
- ActiveModel::MassAssignmentSecurity::BlackList
- ActiveModel::MassAssignmentSecurity::ClassMethods
- ActiveModel::MassAssignmentSecurity::Error
- ActiveModel::MassAssignmentSecurity::LoggerSanitizer
- ActiveModel::MassAssignmentSecurity::PermissionSet
- ActiveModel::MassAssignmentSecurity::Sanitizer
- ActiveModel::MassAssignmentSecurity::StrictSanitizer
- ActiveModel::MassAssignmentSecurity::WhiteList
- ActiveModel::MissingAttributeError
- ActiveModel::Name
- ActiveModel::Naming
- ActiveModel::Observer
- ActiveModel::ObserverArray
- ActiveModel::Observing
- ActiveModel::Observing::ClassMethods
- ActiveModel::SecurePassword
- ActiveModel::SecurePassword::ClassMethods
- ActiveModel::SecurePassword::InstanceMethodsOnActivation
- ActiveModel::Serialization
- ActiveModel::Serializers
- ActiveModel::Serializers::JSON
- ActiveModel::Serializers::Xml
- ActiveModel::StrictValidationFailed
- ActiveModel::Translation
- ActiveModel::Validations
- ActiveModel::Validations::AcceptanceValidator
- ActiveModel::Validations::Callbacks
- ActiveModel::Validations::Callbacks::ClassMethods
- ActiveModel::Validations::ClassMethods
- ActiveModel::Validations::ConfirmationValidator
- ActiveModel::Validations::ExclusionValidator
- ActiveModel::Validations::FormatValidator
- ActiveModel::Validations::HelperMethods
- ActiveModel::Validations::InclusionValidator
- ActiveModel::Validations::LengthValidator
- ActiveModel::Validations::NumericalityValidator
- ActiveModel::Validations::PresenceValidator
- ActiveModel::Validations::WithValidator
- ActiveModel::Validator

No matching classes.

# ActiveModel::Validations::ClassMethods

### Public Instance Methods

attribute_method?(attribute) click to toggle source

Check if method is an attribute method or not.

    # File lib/active_model/validations.rb, line 157
    def attribute_method?(attribute)
      method_defined?(attribute)
    end

inherited(base) click to toggle source

Copy validators on inheritance.

    # File lib/active_model/validations.rb, line 162
    def inherited(base)
      dup = _validators.dup
      base._validators = dup.each { |k, v| dup[k] = v.dup }
      super
    end

validate(*args, &block) click to toggle source

Adds a validation method or block to the class. This is useful when overriding the `validate` instance method becomes too unwieldy and you're looking for more descriptive declaration of your validations.

This can be done with a symbol pointing to a method:

    class Comment
      include ActiveModel::Validations

      validate :must_be_friends

      def must_be_friends
        errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
      end
    end

With a block which is passed with the current record to be validated:

    class Comment
      include ActiveModel::Validations

      validate do |comment|
        comment.must_be_friends
      end

      def must_be_friends
        errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
      end
    end

Or with a block where self points to the current record to be validated:

    class Comment
      include ActiveModel::Validations

      validate do
        errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
      end
    end

    # File lib/active_model/validations.rb, line 132
    def validate(*args, &block)
      options = args.extract_options!
      if options.key?(:on)
        options = options.dup
        options[:if] = Array.wrap(options[:if])
        options[:if].unshift("validation_context == :#{options[:on]}")
      end
      args << options
      set_callback(:validate, *args, &block)
    end

validates(*attributes) click to toggle source

This method is a shortcut to all default validators and any custom validator classes ending in 'Validator'. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as PresenceValidator.

Examples of using the default rails validators:

    validates :terms, :acceptance => true
    validates :password, :confirmation => true
    validates :username, :exclusion => { :in => %w(admin superuser) }
    validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }
    validates :age, :inclusion => { :in => 0..9 }
    validates :first_name, :length => { :maximum => 30 }
    validates :age, :numericality => true
    validates :username, :presence => true
    validates :username, :uniqueness => true

The power of the `validates` method comes when using custom validators and default validators in one call for a given attribute e.g.

    class EmailValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors.add attribute, (options[:message] || "is not an email") unless
          value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      end
    end

    class Person
      include ActiveModel::Validations
      attr_accessor :name, :email

      validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
      validates :email, :presence => true, :email => true
    end

Validator classes may also exist within the class being validated allowing custom modules of validators to be included as needed e.g.

    class Film
      include ActiveModel::Validations

      class TitleValidator < ActiveModel::EachValidator
        def validate_each(record, attribute, value)
          record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
        end
      end

      validates :name, :title => true
    end

Additionally validator classes may be in another namespace and still used within any class.

    validates :name, :'film/title' => true

The validators hash can also handle regular expressions, ranges, arrays and strings in shortcut form, e.g.

    validates :email, :format => /@/
    validates :gender, :inclusion => %w(male female)
    validates :password, :length => 6..20

When using shortcut form, ranges and arrays are passed to your validator's initializer as +options+ while other types including regular expressions and strings are passed as +options+

Finally, the options `:if`, `:unless`, `:on`, `:allow_blank`, `:allow_nil` and `:strict` can be given to one specific validator, as a hash:

    validates :password, :presence => { :if => :password_required? }, :confirmation => true

Or to all at the same time:

    validates :password, :presence => true, :confirmation => true, :if => :password_required?

    # File lib/active_model/validations/validates.rb, line 81
    def validates(*attributes)
      defaults = attributes.extract_options!
      validations = defaults.slice!(*_validates_default_keys)

      raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
      raise ArgumentError, "You need to supply at least one validation" if validations.empty?

      defaults.merge!(:attributes => attributes)

      validations.each do |key, options|
        key = "#{key.to_s.camelize}Validator"

        begin
          validator = key.include?('::') ? key.constantize : const_get(key)
        rescue NameError
          raise ArgumentError, "Unknown validator: '#{key}'"
        end

        validates_with(validator, defaults.merge(_parse_validates_options(options)))
      end
    end

validates!(*attributes) click to toggle source

This method is used to define validation that cannot be corrected by end user and is considered exceptional. So each validator defined with bang or `:strict` option set to `true` will always raise `ActiveModel::StrictValidationFailed` instead of adding error when validation fails. See `validates` for more information about validation itself.

    # File lib/active_model/validations/validates.rb, line 109
    def validates!(*attributes)
      options = attributes.extract_options!
      options[:strict] = true
      validates(*(attributes << options))
    end

validates_each(*attr_names, &block) click to toggle source

Validates each attribute against a block.

    class Person
      include ActiveModel::Validations

      attr_accessor :first_name, :last_name

      validates_each :first_name, :last_name do |record, attr, value|
        record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
      end
    end

Options:

- `:on` - Specifies the context where this validation is active (e.g. `:on => :create` or `:on => :custom_validation_context`)

- `: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.

    # File lib/active_model/validations.rb, line 87
    def validates_each(*attr_names, &block)
      options = attr_names.extract_options!.symbolize_keys
      validates_with BlockValidator, options.merge(:attributes => attr_names.flatten), &block
    end

validates_with(*args, &block) click to toggle source

If you pass any additional configuration options, they will be passed to the class and available as `options`:

    class Person
      include ActiveModel::Validations
      validates_with MyValidator, :my_custom_key => "my custom value"
    end

    class MyValidator < ActiveModel::Validator
      def validate(record)
        options[:my_custom_key] # => "my custom value"
      end
    end

    # File lib/active_model/validations/with.rb, line 79
    def validates_with(*args, &block)
      options = args.extract_options!
      args.each do |klass|
        validator = klass.new(options, &block)
        validator.setup(self) if validator.respond_to?(:setup)

        if validator.respond_to?(:attributes) && !validator.attributes.empty?
          validator.attributes.each do |attribute|
            _validators[attribute.to_sym] << validator
          end
        else
          _validators[nil] << validator
        end

        validate(validator, options)
      end
    end

validators() click to toggle source

List all validators that are being used to validate the model using `validates_with` method.

    # File lib/active_model/validations.rb, line 145
    def validators
      _validators.values.flatten.uniq
    end

validators_on(*attributes) click to toggle source

List all validators that being used to validate a specific attribute.

    # File lib/active_model/validations.rb, line 150
    def validators_on(*attributes)
      attributes.map do |attribute|
        _validators[attribute.to_sym]
      end.flatten
    end

### Protected Instance Methods

_validates_default_keys() click to toggle source

When creating custom validators, it might be useful to be able to specify additional default keys. This can be done by overwriting this method.

    # File lib/active_model/validations/validates.rb, line 119
    def _validates_default_keys
      [:if, :unless, :on, :allow_blank, :allow_nil , :strict]
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.