Validating Date and Time Objects in Rails

Posted by Vincent Woo Sat, 23 Dec 2006 04:07:00 GMT

How does Rails handle non-existing date input? If it’s obviously wrong, such as Dec 345, it’ll error out. If fed Feb 31, however, it’ll try to adjust and goes along its merry way saving Mar 3 to the database without any notice at all. I find that unacceptable and that problem would go away if we could coerce the model into keeping all the individual date param pieces.

We could hijack active record’s multiparameter processing into saving the result into an instance variable:
 def extract_callstack_for_multiparameter_attributes(pairs)
   @multiparameter_attributes = super
 end

And then use them in our custom validations:

if @multiparameter_attributes
  args = @multiparameter_attributes['birthdate'] 
  if args && Date.valid_civil?(*args).nil?
    errors.add('birthdate', args.join('-') + " is not a valid civil date")
  end
end

Posted in  | Tags , ,  | no comments | no trackbacks

Comments

Trackbacks

Use the following link to trackback from your own site:
http://www.undefinedrange.com/trackbacks?article_id=validating-date-and-time-objects-in-rails&day=22&month=12&year=2006

Comments are disabled