This week on a project I had the need to signal the user when they had entered an invalid date for a date field that wasn’t required. But I needed to show the error even if they entered a bunch of garbage into the field. Unfortunately in Rails, if you attempt to set a string into a Date field it doesn’t set at all, and so when the validator fires there is nothing to validate and since the field isn’t a required field, no error is displayed.

After searching the net extensively, I found this ruby class for adding a validates_dates function. It is very helpful and not only solved my problem, but also gives the users a few shortcuts for entering the date, such as the following examples.

+6days, +6d, +6, +2w, -6m, +1y

It also allows you to define, in the validation usage, a from and to range that the date should be within. For example, a person’s renewal date should not be before their created_at date, or limiting a date field to be beyond today.

validates_dates :birthday, :from => '1 Jan 1920', :to => Date.today, :allow_nil => true

The snippet is here.