Tiago Veloso
Tiago Veloso

Reputation: 8563

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.

Upvotes: 6

Views: 16198

Answers (2)

boulder_ruby
boulder_ruby

Reputation: 39695

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

Upvotes: 3

Lucas
Lucas

Reputation: 2886

See that post: Rails 3 Datetime validation

and also:

Rails 3 custom validation between datetime :)

Upvotes: 6

Related Questions