Module: ActiveModel::Validations

Extended by:
ActiveSupport::Concern
Included in:
API
Defined in:
activemodel/lib/active_model/validations.rb,
activemodel/lib/active_model/validations/with.rb,
activemodel/lib/active_model/validations/format.rb,
activemodel/lib/active_model/validations/length.rb,
activemodel/lib/active_model/validations/absence.rb,
activemodel/lib/active_model/validations/presence.rb,
activemodel/lib/active_model/validations/callbacks.rb,
activemodel/lib/active_model/validations/clusivity.rb,
activemodel/lib/active_model/validations/exclusion.rb,
activemodel/lib/active_model/validations/inclusion.rb,
activemodel/lib/active_model/validations/validates.rb,
activemodel/lib/active_model/validations/acceptance.rb,
activemodel/lib/active_model/validations/comparison.rb,
activemodel/lib/active_model/validations/confirmation.rb,
activemodel/lib/active_model/validations/numericality.rb,
activemodel/lib/active_model/validations/comparability.rb,
activemodel/lib/active_model/validations/resolve_value.rb,
activemodel/lib/active_model/validations/helper_methods.rb

Overview

Active Model Validations

Provides a full validation framework to your objects.

A minimal implementation could be:

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.start_with?("z")
  end
end

Which provides you with the full standard validation stack that you know from Active Record:

person = Person.new
person.valid?                   # => true
person.invalid?                 # => false

person.first_name = 'zoolander'
person.valid?                   # => false
person.invalid?                 # => true
person.errors.messages          # => {first_name:["starts with z."]}

Note that ActiveModel::Validations automatically adds an errors method to your instances initialized with a new ActiveModel::Errors object, so there is no need for you to do this manually.

Defined Under Namespace

Modules: Callbacks, ClassMethods, Clusivity, Comparability, HelperMethods, ResolveValue Classes: AbsenceValidator, AcceptanceValidator, ComparisonValidator, ConfirmationValidator, ExclusionValidator, FormatValidator, InclusionValidator, LengthValidator, NumericalityValidator, PresenceValidator, WithValidator

Instance Method Summary collapse

Methods included from ActiveSupport::Concern

append_features, class_methods, extended, included, prepend_features, prepended

Instance Method Details

#errorsObject

Returns the Errors object that holds all information about attribute error messages.

class Person
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name
end

person = Person.new
person.valid? # => false
person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>


334
335
336
# File 'activemodel/lib/active_model/validations.rb', line 334

def errors
  @errors ||= Errors.new(self)
end

#freezeObject



378
379
380
381
382
383
# File 'activemodel/lib/active_model/validations.rb', line 378

def freeze
  errors
  context_for_validation

  super
end

#initialize_dup(other) ⇒ Object

Clean the Errors object if instance is duped.



316
317
318
319
# File 'activemodel/lib/active_model/validations.rb', line 316

def initialize_dup(other) # :nodoc:
  @errors = nil
  super
end

#invalid?(context = nil) ⇒ Boolean

Performs the opposite of valid?. Returns true if errors were added, false otherwise.

class Person
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name
end

person = Person.new
person.name = ''
person.invalid? # => true
person.name = 'david'
person.invalid? # => false

Context can optionally be supplied to define which callbacks to test against (the context is defined on the validations using :on).

class Person
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name, on: :new
end

person = Person.new
person.invalid?       # => false
person.invalid?(:new) # => true

Returns:

  • (Boolean)


414
415
416
# File 'activemodel/lib/active_model/validations.rb', line 414

def invalid?(context = nil)
  !valid?(context)
end

#read_attribute_for_validation(attribute) ⇒ Object

Hook method defining how an attribute value should be retrieved. By default this is assumed to be an instance named after the attribute. If the attribute does not exist, nil is returned. Override this method in subclasses should you need to retrieve the value for a given attribute differently:

class MyClass
  include ActiveModel::Validations

  def initialize(data = {})
    @data = data
  end

  def read_attribute_for_validation(key)
    @data[key]
  end
end


443
444
445
# File 'activemodel/lib/active_model/validations.rb', line 443

def read_attribute_for_validation(attribute)
  send(attribute) if respond_to?(attribute, true)
end

#valid?(context = nil) ⇒ Boolean Also known as: validate

Runs all the specified validations and returns true if no errors were added otherwise false.

class Person
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name
end

person = Person.new
person.name = ''
person.valid? # => false
person.name = 'david'
person.valid? # => true

Context can optionally be supplied to define which callbacks to test against (the context is defined on the validations using :on).

class Person
  include ActiveModel::Validations

  attr_accessor :name
  validates_presence_of :name, on: :new
end

person = Person.new
person.valid?       # => true
person.valid?(:new) # => false

Returns:

  • (Boolean)


367
368
369
370
371
372
373
374
# File 'activemodel/lib/active_model/validations.rb', line 367

def valid?(context = nil)
  current_context = validation_context
  context_for_validation.context = context
  errors.clear
  run_validations!
ensure
  context_for_validation.context = current_context
end

#validate!(context = nil) ⇒ Object

Runs all the validations within the specified context. Returns true if no errors are found, raises ValidationError otherwise.

Validations with no :on option will run no matter the context. Validations with some :on option will only run in the specified context.



423
424
425
# File 'activemodel/lib/active_model/validations.rb', line 423

def validate!(context = nil)
  valid?(context) || raise_validation_error
end

#validates_with(*args, &block) ⇒ Object

Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions.

class Person
  include ActiveModel::Validations

  validate :instance_validations

  def instance_validations
    validates_with MyValidator
  end
end

Please consult the class method documentation for more information on creating your own validator.

You may also pass it multiple classes, like so:

class Person
  include ActiveModel::Validations

  validate :instance_validations, on: :create

  def instance_validations
    validates_with MyValidator, MyOtherValidator
  end
end

Standard configuration options (:on, :if and :unless), which are available on the class version of validates_with, should instead be placed on the validates method as these are applied and tested in the callback.

If you pass any additional configuration options, they will be passed to the class and available as options, please refer to the class version of this method for more information.



144
145
146
147
148
149
150
151
152
# File 'activemodel/lib/active_model/validations/with.rb', line 144

def validates_with(*args, &block)
  options = args.extract_options!
  options[:class] = self.class

  args.each do |klass|
    validator = klass.new(options.dup, &block)
    validator.validate(self)
  end
end

#validation_contextObject

Returns the context when running validations.



448
449
450
# File 'activemodel/lib/active_model/validations.rb', line 448

def validation_context
  context_for_validation.context
end