3

Using regular expression, how would I validate a date to make sure it is only entered in this format: mm/dd/yyyy?

If anyone is interested, I'm using validates_format_of :date_field, :with => // in a Ruby model.

4
  • 1
    A regex really isn't the right tool for this job, DateTime.strptime with the appropriate format string and an exception handler would be much better. Commented Nov 17, 2011 at 20:40
  • What I need to do is validate a string that should be formatted like : (2 numbers)/(2 numbers)/(4 numbers). Commented Nov 17, 2011 at 20:44
  • 1
    But "20/20/2020" is not a valid date. Commented Nov 17, 2011 at 20:46
  • You're right. But I don't mind, as long as it's entered in that format. Commented Nov 17, 2011 at 21:01

2 Answers 2

5

Regex for this format can looks like:

^\d{2}\/\d{2}\/\d{4}$
2
  • I think you made a mistake in the regular expression. You need to remove the extra `\`. I tried to fix the mistake but the changes were reset back to what it was. Commented Nov 17, 2011 at 21:16
  • The main mistake is related to line endings: homakov.blogspot.ru/2012/05/… Commented Dec 28, 2015 at 7:37
3

@hsz answer is correct. Should you need to also validate the date itself you can use this :

/^(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[1-2]\d|3[01])/\d{4}$/

Edit :

As @Tim said this will is not a 100% regex validator. See his linked answer for that.

if subject =~ /\A(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|[1-2]\d|3[01])\/\d{4}\Z/
    # Successful match

Edit #2 : Ruby specific version above.

3
  • 2
    This only gets you halfway there - 02/31/1234 would pass and many other invalid dates - for a true date validation that takes leap years into account, you'd need a huge regex (which is possible, but not a good idea). Better leave validation to a specialized function. Commented Nov 17, 2011 at 20:23
  • @TimPietzcker I wouldn't do this with regex. I am sure there are modules for this, or other better ways.
    – FailedDev
    Commented Nov 17, 2011 at 20:36
  • You might need to escape the / characters. Commented Nov 17, 2011 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.