Daniel Morrison

Keep your dates in order with validates_chronological

I think I’ve written code to do this at least 3 times, so today I tried to do it right. Let’s say you have a Rails model with a couple dates (any event with beginning and end will do). You generally want to make sure it ends after it begins.

validates_chronological :begin_time, :end_time

If you try to set end_time before begin_time, you’ll get an error like:

1 errors prohibited this event from being saved

There were problems with the following fields:

  • End time is not in chronological order

It will handle more than 2 fields and is configurable as you’d expect.

Grab the code, which is now part of a plugin we’ll talk about more in the next few weeks.

Make a Comment