class ActiveModel::Validator
class level validates_with
method.
This setup method is only called when used with validation macros or the
end
end
klass.send :attr_accessor, :custom_attribute
def setup(klass)
class MyValidator < ActiveModel::Validator
for example:
useful when there are prerequisites such as an attr_accessor being present
with the class that using that validator as it’s argument. This can be
Validator may also define a setup
instance method which will get called
end
validates :title, :presence => true, :title => true
attr_accessor :title
include ActiveModel::Validations
class Person
(see ActiveModel::Validations::ClassMethods.validates for more on this)
This can now be used in combination with the validates
method<br><br>end<br>end<br>record.errors << ‘must be Mr. Mrs. or Dr.’ unless [‘Mr.’, ‘Mrs.’, ‘Dr.’].include?(value)
def validate_each(record, attribute, value)
class TitleValidator < ActiveModel::EachValidator
is with the convenient ActiveModel::EachValidator for example:
The easiest way to add custom validators for validating individual attributes
end
end
@my_custom_field = options || :first_name
super
def initialize(record, options)
class MyValidator < ActiveModel::Validator
To add behavior to the initialize method, use the following signature:
end
end
# etc…<br>record.errors << “This is some complex validation”<br>record.errors << “This is some custom error message”
def validate(record)
class MyValidator < ActiveModel::Validator
from within the validators message
To cause a validation error, you must add to the record
‘s errors directly
end
end
options # => Any non-standard options passed to validates_with
record # => The person instance being validated
def validate(record)
class MyValidator < ActiveModel::Validator
end
validates_with MyValidator
include ActiveModel::Validations
class Person
called validate
which accepts a record
.
Any class that inherits from ActiveModel::Validator must implement a method
end
end
# …
def some_complex_logic<br>private<br><br>end<br>end<br>record.errors = “This record is invalid”
if some_complex_logic
def validate(record)
class MyValidator < ActiveModel::Validator
end
validates_with MyValidator
include ActiveModel::Validations
class Person
ActiveModel::Validations::ClassMethods.validates_with
A simple base class that can be used along with
== Active Model Validator
def self.kind
UniquenessValidator.kind # => :uniqueness
PresenceValidator.kind # => :presence
== Examples
Returns the kind of the validator.
def self.kind @kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous? end
def initialize(options)
def initialize(options) @options = options.freeze end
def kind
def kind self.class.kind end
def validate(record)
Override this method in subclasses with validation logic, adding errors
def validate(record) raise NotImplementedError end