Handling Illegal Dates When User Enters Date

For my website when a user creates an account they have to fill out their birthdate using pulldown menus. If a user enters an illegal date the system throws an error before I even get the opportunity to validate the date in the user model on save.

Soon as I do the following in my controller:

@user = User.new(params[:user])

The following error is thrown:

1 error(s) on assignment of multiparameter attributes

How are people handling situations like this… what is the best practice? I don’t personaly want to do validation outside of the model… that would just suck :-p. Thanks for any input you might have!

Thanks :-).

Here's what I've done:

  begin       @user = User.new(params[:user])   rescue ActiveRecord::MultiparameterAssignmentErrors       # date is invalid, so reset these fields before creating new user object       params[:user]['date_of_birth(1i)'] = ''       params[:user]['date_of_birth(2i)'] = ''       params[:user]['date_of_birth(3i)'] = ''       # try again, letting our model's validates_presence_of :date_of_birth       # handle things.       @user = User.new(params[:user])   end

By the way, I neglected to mention the fact that this code goes in your controller. Also, the formatting got messed up, but I think you can still get the gist of it.

Your solution makes sense… but isn’t the problem with this that you are not adding an error onto your model’s error stack so a proper error is not being displayed? I am assuming their is more “Rails Way” of handling this… no?

Good point. While it's still controller centric, here's another pass, with a specific error on the date_of_birth field:

begin   @user = User.new(params[:user]) rescue ActiveRecord::MultiparameterAssignmentErrors   # date is invalid, so reset these fields before creating new user object   params[:user]['date_of_birth(1i)'] = ''   params[:user]['date_of_birth(2i)'] = ''   params[:user]['date_of_birth(3i)'] = ''   # try again, letting our model's validates_presence_of :date_of_birth   # handle things.   @user = User.new(params[:user])

  # Adding a specific error:   @user.errors.add(:date_of_birth, "was invalid") end