Module: ActiveModel::Validations
Overview
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. # => {first_name:["starts with z."]}
Note that Validations
automatically adds an #errors method to your instances initialized with a new Errors
object, so there is no need for you to do this manually.
Class Method Summary
::ActiveSupport::Concern
- Extended
class_methods | Define class methods from given block. |
included | Evaluate given block in context of base class, so that you can write class macros here. |
prepended | Evaluate given block in context of base class, so that you can write class macros here. |
append_features, prepend_features |
Instance Attribute Summary
-
#validation_context
rw
Returns the context when running validations.
- #validation_context=(context) rw private
Instance Method Summary
-
#errors
Returns the
Errors
object that holds all information about attribute error messages. - #freeze
-
#invalid?(context = nil) ⇒ Boolean
Performs the opposite of #valid?.
-
#read_attribute_for_validation
Hook method defining how an attribute value should be retrieved.
-
#valid?(context = nil) ⇒ Boolean
(also: #validate)
Runs all the specified validations and returns
true
if no errors were added otherwisefalse
. -
#validate(context = nil)
Alias for #valid?.
-
#validate!(context = nil)
Runs all the validations within the specified context.
-
#validates_with(*args, &block)
Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions.
- #context_for_validation private
- #init_internals private
- #raise_validation_error private
- #run_validations! private
-
#initialize_dup(other)
Internal use only
Clean the
Errors
object if instance is duped.
DSL Calls
included
[ GitHub ]40 41 42 43 44 45 46 47 48 49 50 51
# File 'activemodel/lib/active_model/validations.rb', line 40
included do extend ActiveModel::Naming extend ActiveModel::Callbacks extend ActiveModel::Translation extend HelperMethods include HelperMethods define_callbacks :validate, scope: :name class_attribute :_validators, instance_writer: false, default: Hash.new { |h, k| h[k] = [] } end
Instance Attribute Details
#validation_context (rw)
Returns the context when running validations.
This is useful when running validations except a certain context (opposite to the on
option).
class Person
include ActiveModel::Validations
attr_accessor :name
validates :name, presence: true, if: -> { validation_context != :custom }
end
person = Person.new
person.valid? #=> false
person.valid?(:new) #=> false
person.valid?(:custom) #=> true
# File 'activemodel/lib/active_model/validations.rb', line 454
def validation_context context_for_validation.context end
#validation_context=(context) (rw, private)
[ GitHub ]# File 'activemodel/lib/active_model/validations.rb', line 459
def validation_context=(context) context_for_validation.context = context end
Instance Method Details
#context_for_validation (private)
[ GitHub ]# File 'activemodel/lib/active_model/validations.rb', line 463
def context_for_validation @context_for_validation ||= ValidationContext.new end
#errors
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"]}>
#freeze
[ GitHub ]# File 'activemodel/lib/active_model/validations.rb', line 372
def freeze errors context_for_validation super end
#init_internals (private)
[ GitHub ]# File 'activemodel/lib/active_model/validations.rb', line 467
def init_internals super @errors = nil @context_for_validation = nil end
#initialize_dup(other)
Clean the Errors
object if instance is duped.
# File 'activemodel/lib/active_model/validations.rb', line 310
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
# File 'activemodel/lib/active_model/validations.rb', line 408
def invalid?(context = nil) !valid?(context) end
#raise_validation_error (private)
# File 'activemodel/lib/active_model/validations.rb', line 478
def raise_validation_error # :doc: raise(ValidationError.new(self)) end
#read_attribute_for_validation
Hook method defining how an attribute value should be retrieved. By default this is assumed to be an instance named after the attribute. 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
# File 'activemodel/lib/active_model/validations.rb', line 437
alias :read_attribute_for_validation :send
#run_validations! (private)
[ GitHub ]# File 'activemodel/lib/active_model/validations.rb', line 473
def run_validations! _run_validate_callbacks errors.empty? 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
# File 'activemodel/lib/active_model/validations.rb', line 361
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)
Alias for #valid?.
# File 'activemodel/lib/active_model/validations.rb', line 370
alias_method :validate, :valid?
#validate!(context = nil)
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.
# File 'activemodel/lib/active_model/validations.rb', line 417
def validate!(context = nil) valid?(context) || raise_validation_error end
#validates_with(*args, &block)
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.
# File 'activemodel/lib/active_model/validations/with.rb', line 144
def validates_with(*args, &block) = args. [:class] = self.class args.each do |klass| validator = klass.new( .dup, &block) validator.validate(self) end end