$ rails generate validates_timeliness:install
会生成 initializer 和 locale 配置文件!
validates_datetime :occurred_at
validates_date :date_of_birth, :before => lambda { 18.years.ago },
:before_message => "must be at least 18 years old"
validates_datetime :finish_time, :after => :start_time # Method symbol
validates_date :booked_at, :on => :create, :on_or_after => :today # See Restriction Shorthand.
validates_time :booked_at, :between => ['9.00am', '5:00pm']
validates_time :breakfast_time, :on_or_after => '6:00am',
:on_or_after_message => 'must be after opening time',
:before => :lunchtime,
:before_message => 'must be before lunch time'
class Person < ActiveRecord::Base
validates_date :date_of_birth, :on_or_before => lambda { Date.current }
# or
validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.current }, :type => :date}
end
# or even on a specific record, per ActiveModel API.
@person.validates_date :date_of_birth, :on_or_before => lambda { Date.current }
其实和平常的‘校验’也没什么两样,只是我们对 日期/时间的校验 不常用罢了。如下:
validates_date - validate value as date
validates_time - validate value as time only i.e. '12:20pm'
validates_datetime - validate value as a full date and time
validates - use the :timeliness key and set the type in the hash.
对于上面的 validates
方法,我们可以有如下选项:
:is_at - Attribute must be equal to value to be valid
:before - Attribute must be before this value to be valid
:on_or_before - Attribute must be equal to or before this value to be valid
:after - Attribute must be after this value to be valid
:on_or_after - Attribute must be equal to or after this value to be valid
:between - Attribute must be between the values to be valid. Range or Array of 2 values.
:allow_nil - Allow a nil value to be valid
:allow_blank - Allows a nil or empty string value to be valid
:if - Execute validation when :if evaluates true
:unless - Execute validation when :unless evaluates false
:on - Specify validation context e.g :save, :create or :update. Default is :save.
:ignore_usec - Ignores microsecond value on datetime restrictions
:format - Limit validation to a single format for special cases. Requires plugin parser.