Validating Date and Time Objects in Rails
Posted by Vincent Woo
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






