0

I have this regex to check date entry:

/^[0-9]{2}-[0-9]{2}-[0-9]{4}$|^$/

I also need it to make sure that the format MM-DD-YYYY is followed.
I've tried these and they don't work.

/^[01-12]-[01-31]-[0-9]{4}$|^$/
/^['01'-'12']-['01'-'31']-[0-9]{4}$|^$/

How can I make this also check to make sure the MM part is 01-12 and the DD part is only
01-31?

Ivan Koblik
  • 4,285
  • 1
  • 30
  • 33
MB34
  • 4,210
  • 12
  • 59
  • 110
  • try this one: http://stackoverflow.com/questions/5465375/javascript-date-regex-dd-mm-yyyy – Zim84 May 03 '13 at 13:46
  • It does not seem like you are really after date check. 30th of Februari would be valid for example. – ahdaniels May 03 '13 at 13:48
  • @Zim84, I modified the one there an it worked, please post as answer and I'll accept. – MB34 May 03 '13 at 13:55
  • @Juhana, not duplicate, the one on link that Zim84 posted worked great. Oh, BTW, thanks for the downvote by referring to the other post. – MB34 May 03 '13 at 13:58
  • @ahdaniels, not really concerned about 30 of Feb. – MB34 May 03 '13 at 14:04
  • ok, made a post. thx :) – Zim84 May 03 '13 at 14:10
  • It's pretty hard to believe the duplicate would not work if the other did. I also can't see how the downvote is my fault. – JJJ May 03 '13 at 14:28
  • Not duplicate answers, that's for sure. Look at the one Zim84 provided, it is the one that led me to the solution. When you flag as duplicate it automatically gives a downvote. – MB34 May 03 '13 at 20:25
  • No, it doesn't. Flagging for spam gives a downvote, other flags don't. (And I didn't even flag but voted to close.) – JJJ May 03 '13 at 20:51

3 Answers3

0

try this

/^[0-1]{1}[1-2]{1}-[0-3]{1}[1-2]{1}-[0-9]{4}$|^$/
NPKR
  • 5,368
  • 4
  • 31
  • 48
  • I think it invalidates anything starting with 10 or has 30 in the date(day) and validates date of 32. Should it not be /^[0-1]{1}[0-2]{1}-[0-3]{1}[01]{1}-[0-9]{4}$|^$/ It'll still say 31st of Feb is valid or 00 of 00 but it's close. – HMR May 03 '13 at 14:01
0

Kind of crazy going with pure regex, i would go with regex + condition check as follows:

  1. check with regex /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/
  2. // assuming myDate is ur string

    var dateParts = myDate.split('-'); var bDateIsValid = ( Number( dateParts[0] ) <= 12 && Number( dateParts[0] ) >=1 ) && ( Number( dateParts[1] ) <= 31 && Number( dateParts[1] ) >=1 )

You may add also date if you wish

Marek Lewandowski
  • 3,291
  • 1
  • 20
  • 26
0

This is a regex that could help you: Javascript date regex DD/MM/YYYY

Please consider converting the string-to-validate into a date-object and see if its valid. This will actually validate it and will not accept dates like 31-02-9999

Community
  • 1
  • 1
Zim84
  • 3,404
  • 2
  • 35
  • 40