Module: AWS::Record::Validations
- Defined in:
- lib/aws/record/validations.rb
Overview
Validation methods to be used with subclasses of AWS::Record::Model.
General Usage
All standard validation methods follow the same basic usage. Call the validation method followed by one more attribute names and then an optional hash of modifiers.
class Book < AWS::Record::Model
# ...
validates_presence_of :title, :author
validates_length_of :summary,
:max => 500,
:allow_nil => true
end
Conditional Validations
Sometimes you only want to validate an attribute under certain conditions. To make this simple, all validation methods accept the following 3 options:
-
:on
-
:if
-
:unless
You may mix and match all 3 of the above options.
Validate on :create or :update
By default validations are run on create and update, but you can specify them to run for only create (initial save) or updates.
validates_presence_of :created_at, :on => :create
validates_presence_of :updated_at, :on => :update
Validate :if or :unless
Sometimes you have more complex requirements to determine if/when a validation should run. :if
and :unless
: both accept either a method name or proc.
class Person
# ...
validates_presence_of :job_title, :if => :employee?
validates_presence_of :nickname, :if => lambda {|person|
person.is_family? or person.is_friend? }
end
Validating Virtual (Non-persisted) Attributes
All of the validators can be used with configured attributes, but they can also be used with any attribute that has a setter and a getter.
Class Book < AWS::Record::Model
attr_accessor :title
validates_presence_of :title
end
Class Method Summary collapse
Instance Method Summary collapse
-
#validate(*method_names, options = {}) ⇒ Object
Registers a validation method.
-
#validates_acceptance_of(*attributes, options = {}, &block) ⇒ Object
This validation method is primariliy intended for ensuring a form checkbox (like an EULA agreement or terms of service acknowledgement) is checked.
-
#validates_confirmation_of(*attributes, options = {}, &block) ⇒ Object
Intended primarily for validating a form field was entered correctly by requiring it twice:.
-
#validates_count_of(*attributes, options = {}, &block) ⇒ Object
Validates the number of values for a given attribute.
-
#validates_each(*attributes, options = {}, &block) ⇒ Object
Adds a block validator that is called during record validation.
-
#validates_exclusion_of(*attributes, options = {}, &block) ⇒ Object
Validates that the attribute value is not included in the given enumerable.
-
#validates_format_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute’s value matches the given regular exression.
-
#validates_inclusion_of(*attributes, options = {}, &block) ⇒ Object
Validates that the attribute value is included in the given enumerable object.
-
#validates_length_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute values are of a specified length.
-
#validates_numericality_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute has a numeric value.
-
#validates_presence_of(*attributes, options = {}, &block) ⇒ Object
Validates the named attributes are not blank.
Class Method Details
.extended(base) ⇒ Object
102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/aws/record/validations.rb', line 102 def self.extended base base.send(:define_method, :run_validations) do errors.clear! self.class.send(:validators).each do |validator| validator.validate(self) end end base.send(:private, :run_validations) end |
Instance Method Details
#validate(*method_names, options = {}) ⇒ Object
Registers a validation method.
validate :ensure_age_is_greater_than_shoe_size
def ensure_age_is_greater_than_shoe_size
unless age > shoe_size
errors.add(:age, 'should be greater than your shoe size')
end
end
You can also pass a list of method names that should be called during validation.
validate :some_complex_validation, :some_other_validation
As with most other validation methods you can also pass a hash of options that affect when the named validation methods get called.
validate :my_custom_validation, :unless => :new_record?
151 152 153 |
# File 'lib/aws/record/validations.rb', line 151 def validate *args validators << MethodValidator.new(self, *args) end |
#validates_acceptance_of(*attributes, options = {}, &block) ⇒ Object
Most validators default :allow_nil to false, this one defaults to true
This validator should not be used with multi-valued attributes
This validation method is primariliy intended for ensuring a form checkbox (like an EULA agreement or terms of service acknowledgement) is checked.
class User < AWS::Record::Model
boolean_attr :terms_of_service
validates_acceptance_of :terms_of_service
end
Virtual Attributes
If you choose to validate the acceptance of a non-existant attribute then a setter and a getter will be added automtically for you.
class User < AWS::Record::Model
validates_acceptance_of :terms_of_service
end
user = User.new
user.respond_to?(:terms_of_service) #=> true
user.respond_to?(:terms_of_service=) #=> true
Accepted Values
The default behavior for validates_acceptance_of
is to add an error when the value is ‘1’ or true
. Also note, this validation method defaults :allow_nil
to true.
-
nil
implies the field was omitted from the form and therefore should not be validatedclass User < AWS::Record::Model validates_acceptance_of :terms_of_service end u = User.new u.terms_of_service #=> nil u.valid? #=> true
-
‘1’ is the default value for most checkbox form helpers, and # therefore indicates an accepted value.
-
true
is how boolean attributes typecast ‘1’. This is helpful when you have your checkbox post its value to a:boolean_attr
.
Multi-Valued Attributes
This validator works only with single-valued attributes. If you need to validate that all of the values in a set are true, then use #validates_inclusion_of.
232 233 234 |
# File 'lib/aws/record/validations.rb', line 232 def validates_acceptance_of *args validators << AcceptanceValidator.new(self, *args) end |
#validates_confirmation_of(*attributes, options = {}, &block) ⇒ Object
This validation method does not accept the :allow_nil
option.
Intended primarily for validating a form field was entered correctly by requiring it twice:
Model:
class User < AWS::Record::Model
validates_confirmation_of :password, :if => :password_changed?
end
View:
<%= password_field "user", "password" %>
<%= password_field "user", "password_confirmation" %>
Confirmation Value Accessors
If your model does not have accessors for the confirmation value then they will be automatically added. In the example above the user class would have an attr_accessor
for :password_confirmation
.
Conditional Validation
Mostly commonly you only need to validate confirmation of an attribute when it has changed. It is therefore suggested to pass an :if
condition reflecting this:
validates_confirmation_of :password, :if => :password_changed?
Multi-Valued Attributes
This validator works only with single-valued attributes. It should not be used on attributes that have array or set values.
287 288 289 |
# File 'lib/aws/record/validations.rb', line 287 def validates_confirmation_of *args validators << ConfirmationValidator.new(self, *args) end |
#validates_count_of(*attributes, options = {}, &block) ⇒ Object
Validates the number of values for a given attribute.
Length vs Count
validates_count_of
validates the number of attribute values, whereas +validates_length_of: validates the length of each attribute value instead.
If you need to ensure each attribute value is a given length see #validates_length_of instead.
Examples
You can validate there are a certain number of values:
validates_count_of :parents, :exactly => 2
You can also specify a range:
validates_count_of :tags, :within => (2..10)
You can also specify min and max value seperately:
validates_count_of :tags, :minimum => 2, :maximum => 10
nil
Values
If you are validating an array or set that contains nil
values, the nil
values are counted normally as 1 each.
If you are validating a non-enuemrable attribute that only contains a single nil or other scalar value, then nil is counted as 0.
Singular Attributes
This validator is intended to for validating attributes that have an array or set of values. If used on an attribute that returns a scalar value (like nil
or a string), the count will always be 0 (for nil
) or 1 (for everything else).
It is therefore recomended to use :validates_presence_of
in place of :validates_count_of
when working with single-valued attributes.
373 374 375 |
# File 'lib/aws/record/validations.rb', line 373 def validates_count_of *args validators << CountValidator.new(self, *args) end |
#validates_each(*attributes, options = {}, &block) ⇒ Object
408 409 410 411 412 413 |
# File 'lib/aws/record/validations.rb', line 408 def validates_each *attributes, &block unless block_given? raise ArgumentError, 'missing required block for validates_each' end validators << BlockValidator.new(self, *attributes, &block) end |
#validates_exclusion_of(*attributes, options = {}, &block) ⇒ Object
Validates that the attribute value is not included in the given enumerable.
validates_exlusion_of :username, :in => %w(admin administrator)
Multi-Valued Attributes
You may use this with multi-valued attributes the same way you use it with single-valued attributes:
class Product < AWS::Record::Model
string_attr :tags, :set => true
validates_exlusion_of :tags, :in => four_letter_words
end
454 455 456 |
# File 'lib/aws/record/validations.rb', line 454 def validates_exclusion_of *args validators << ExclusionValidator.new(self, *args) end |
#validates_format_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute’s value matches the given regular exression.
validates_format_of :year, :with => /^\d{4}$/
You can also perform a not-match using :without
instead of :with
.
validates_format_of :username, :without => /\d/
Multi-Valued Attributes
You may use this with multi-valued attributes the same way you use it with single-valued attributes:
class Product < AWS::Record::Model
string_attr :tags, :set => true
validates_format_of :tags, :with => /^\w{2,10}$/
end
503 504 505 |
# File 'lib/aws/record/validations.rb', line 503 def validates_format_of *args validators << FormatValidator.new(self, *args) end |
#validates_inclusion_of(*attributes, options = {}, &block) ⇒ Object
Validates that the attribute value is included in the given enumerable object.
class MultipleChoiceAnswer < AWS::Record::Model
validates_inclusion_of :letter, :in => %w(a b c d e)
end
Multi-Valued Attributes
You may use this with multi-valued attributes the same way you use it with single-valued attributes.
540 541 542 |
# File 'lib/aws/record/validations.rb', line 540 def validates_inclusion_of *attributes validators << InclusionValidator.new(self, *attributes) end |
#validates_length_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute values are of a specified length.
validates_lenth_of :username, :within => 3..25
Length vs Count
validates_length_of
validates the length of individual attribute values, whereas +validates_count_of: validates the number of attribute values.
If you need to ensure there are certain number of values see #validates_count_of instead.
601 602 603 |
# File 'lib/aws/record/validations.rb', line 601 def validates_length_of *args validators << LengthValidator.new(self, *args) end |
#validates_numericality_of(*attributes, options = {}, &block) ⇒ Object
Validates the attribute has a numeric value.
validates_numericality_of :age, :only_integer => true
Multi-Valued Attributes
You can validate multi-valued attributes using this the same way you validate single-valued attributes. Each value will be validated individually.
651 652 653 |
# File 'lib/aws/record/validations.rb', line 651 def validates_numericality_of *args validators << NumericalityValidator.new(self, *args) end |
#validates_presence_of(*attributes, options = {}, &block) ⇒ Object
Validates the named attributes are not blank. For validation purposes, blank values include:
-
nil
-
empty string
-
anything that responds to #empty? with true
-
anything that responds to #blank? with true
682 683 684 |
# File 'lib/aws/record/validations.rb', line 682 def validates_presence_of *args validators << PresenceValidator.new(self, *args) end |