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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Artem Kalinchuk
  • 6,502
  • 7
  • 43
  • 57

2 Answers2

5

Regex for this format can looks like:

^\d{2}\/\d{2}\/\d{4}$
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 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. – Artem Kalinchuk Nov 17 '11 at 21:16
  • The main mistake is related to line endings: http://homakov.blogspot.ru/2012/05/saferweb-injects-in-various-ruby.html – denis.peplin Dec 28 '15 at 07: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.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • 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](http://stackoverflow.com/questions/4290433/regular-expression-for-aspregularexpressionvalidator-with-format-mmddyy-leap-y/4291747#4291747)). Better leave validation to a specialized function. – Tim Pietzcker Nov 17 '11 at 20:23
  • @TimPietzcker I wouldn't do this with regex. I am sure there are modules for this, or other better ways. – FailedDev Nov 17 '11 at 20:36
  • You might need to escape the `/` characters. – Artem Kalinchuk Nov 17 '11 at 21:17