Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Datetime in rails

I am trying to validate two date fields. I want to validate that the second field is always the same date or any date after the first one.

Example if date1 is 22/05/2011 date2 can not be 20/05/2011.

I am using ruby on rails 3.0.7, and I am trying to do this at the model level.

like image 990
Tiago Veloso Avatar asked May 22 '11 13:05

Tiago Veloso


2 Answers

See that post: Rails 3 Datetime validation

and also:

Rails 3 custom validation between datetime :)

like image 61
Lucas Avatar answered Nov 02 '22 01:11

Lucas


a.) there's an app for that

gem "validates_date_time", :git => "git://github.com/sofatutor/validates_date_time", :branch => 'rails-3'

b.) I'm actually not using that gem because I found this handy model method before the gem

class KeyPerson < ActiveRecord::Base

validate :started_at_is_date?

private

def started_at_is_date?
   if !started_at.is_a?(Date)
     errors.add(:started_at, 'must be a valid date') 
   end
  end
  end

where :started_at is the column's name. That's a little bit of ruby magic/chaos for you with the dynamic method name handling thing

like image 41
boulder_ruby Avatar answered Nov 02 '22 00:11

boulder_ruby