Date validation in Rails
I have an Active Record model that contains two attributes: start_date and end_date. How do I go about validating the following:
- The dates are i开发者_运维知识库n the correct (yyyy-mm-dd) format
- That end_date > start_date
Does it matter what format they are stored in? A Date object is a Date object. Are you storing it in a date column in the DB?
Here is how I do the validation:
class MyModel < ActiveRecord::Base
validate :validate_end_date_before_start_date
def validate_end_date_before_start_date
if end_date && start_date
errors.add(:end_date, "Put error text here") if end_date < start_date
end
end
end
Keep in mind this does not check for nil dates... you might want to if either could be.
FYI, if you want to be able to accept a variety of formats Chronic is pretty flexible.
Here is how to do date validation:
How do I validate a date in rails?
And seeing if a date is greater than another date, you can just use the greater than/less than operators on date objects:
ruby-1.9.2-p136 :006 > d1 = Date.civil(2011, 05, 01)
=> #<Date: 2011-05-01 (4911365/2,0,2299161)>
ruby-1.9.2-p136 :007 > d2 = Date.civil(2011, 01, 01)
=> #<Date: 2011-01-01 (4911125/2,0,2299161)>
ruby-1.9.2-p136 :008 > d2 > d1
=> false
ruby-1.9.2-p136 :009 > d2 < d1
=> true
So in your example:
def validate_dates
errors.add("Created at date", "is invalid.") unless convert_created_at
errors.add("End Date" , "is invalid") if end_date > start_date
end
精彩评论