#35: validating date_select in rails

If you use the date_select helper in Rails, setting all fields except for the year will result in MultiparameterAssignmentErrors. You can catch the exception, but it's kind of hard to catch it in a place where you can add errors to a model instance.

override assign_multiparameter_attributes

I ended up overriding assign_multiparameter_attributes to look for empty fields. Obviously, this will break non-date multiparam assignments, but I'm hoping that will be ok in my case.

In my model:

def assign_multiparameter_attributes(pairs) pair_values = Hash[pairs].values if pair_values.collect(&:blank?).include?(true) && pair_values.collect(&:blank?).uniq.include?(false) @incomplete_date = true else super(pairs) end end def validate if @incomplete_date self.errors.add_to_base("The date you entered is incomplete!") end end

Think you've got a better solution? Help 148c663fd665c53518538e093ce3c2ab_small kueda out by posting your solution

http://giantrobots.thoughtbot.com/2007/5/29/ruby-on-fails - found by 148c663fd665c53518538e093ce3c2ab_small kueda on April 15, 2009, 11:42 PM UTC

Lists the many ways you could approach the problem. My solution was derived from some of the comments. Note that he ended up just not using date_select. Probably the better solution.