FutoRicky FutoRicky - 2 years ago 58
Ruby Question

Why is valid_date? for now is true, but for tomorrow is false?

Doing some validation for dates I found that valid_date? is giving me a false value if the date is in the future (date after current date) but all other dates is true.


These return true:

valid_date? DateTime.strptime(DateTime.yesterday.strftime("%m-%d-%Y"), "%m-%d-%Y")

valid_date? DateTime.strptime(DateTime.now.strftime("%m-%d-%Y"), "%m-%d-%Y")

But this returns false

valid_date? DateTime.strptime(DateTime.tomorrow.strftime("%m-%d-%Y"), "%m-%d-%Y")

Can anyone explain the reason for this?

Answer Source

The most common use for valid_date? is to attach dates that are occuring or occured to models. Therefore future dates aren't valid because it didn't happen yet!


For validating future dates:

If you are using DateTime to construct your dates it will aways give you a valid DateTime.

To parse a date a user entered use either DateTime.strptime or DateTime.parse, you can even set the format using the former. If the parse fails (invalid DateTime) it will give you nil.

Something good about ActiveRecord, if your model knows the field should be a DateTime, the presence validator should be enough as it will try to parse the string for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download