Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. The dates are in the correct (yyyy-mm-dd) format
  2. That end_date > start_date
like image 280
Kevin Pang Avatar asked Apr 14 '11 14:04

Kevin Pang


2 Answers

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.

like image 124
brettish Avatar answered Oct 09 '22 05:10

brettish


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
like image 30
Mike Lewis Avatar answered Oct 09 '22 04:10

Mike Lewis