1

i need a regular expression for an expire date for a visa in the layout MM/DD/YYYY i used

var expire = /(\d{2})+\/(\d{2})+\/(\d{4})/

and i know \d is for digit and the {4} allows for exactly 4 digits so im not really sure what im doing wrong here. thanks for the help

Knitex
  • 225
  • 1
  • 6
  • 11
  • Isn't expiration date just `MM/YYYY`? – zerkms Nov 05 '12 at 19:43
  • You should get rid of the `+` operators after the first two two-digit groups. – Pointy Nov 05 '12 at 19:43
  • Funny, [this site](http://www.regular-expressions.info/javascriptexample.html) says `(\d{2})+\/(\d{2})+\/(\d{4})` matches. – Whymarrh Nov 05 '12 at 19:45
  • @Whymarrh: why shouldn't it? It would match `1111111111/11/1111` as well though – zerkms Nov 05 '12 at 19:46
  • The answer below says the `+` sign causes problems. – Whymarrh Nov 05 '12 at 19:47
  • @Whymarrh: it would give false positives, but still it would match what it expected to match – zerkms Nov 05 '12 at 19:48
  • 1
    Regular expressions for dates is not the best idea because you're validating a format not a _valid date_. Check my answer to [this question](http://stackoverflow.com/questions/11218181/best-way-to-validate-date-string-format-via-jquery/11218271#11218271) if you want to validate the format as well as the date, meaning that `11/31/2012` would be invalid although it has a valid format. – elclanrs Nov 05 '12 at 19:51

2 Answers2

5

It should be:

var expire = /\d{2}\/\d{2}\/\d{4}/;

The + signs are causing the problems.

zerkms
  • 249,484
  • 69
  • 436
  • 539
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
1

This one works for MM/DD/YYYY:

(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(19|20)\d\d

Or this one for DD/MM/YYYY:

(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d\d

Although, they do not cover dates like 31/02/2012...

naeramarth7
  • 6,030
  • 1
  • 22
  • 26
  • "Although, they do not cover dates like 31/02/2012..." --- so, any reason to overcomplicate if you need to perform additional check anyway? Why not create trivial regex and polish it with thorough check on correctness separately – zerkms Nov 05 '12 at 19:48
  • Wouldn't it be more performant to cover it in the regex itself instead of performing another check after? – naeramarth7 Nov 05 '12 at 19:51
  • you still need to perform check, don't you? `31/02/2012` would match your regex and it's not a correct date. – zerkms Nov 05 '12 at 19:54