3

I'm not good at regular expression. I got code to validate dd/mm/yyyy format which also validates leap year, I tried to modify to get it work for mm/dd/yyyy, but they all failed.

Can some one change it to validate mm/dd/yyyy format?

Regular Expression:

^(((0[1-9]|[12]\d|3[01])/(0[13578]|1[02])/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)/(0[13456789]|1[012])/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])/02/((19|[2-9]\d)\d{2}))|(29/02/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

Answer Hi All, thanks for the help from all of you, finally parsing again the regular expression, i got my answer to validate mm/dd/yyyy format

Regular Expression:

/^(((0[13578]|1[02])/(0[1-9]|[12]\d|3[01])/((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])/(0[1-9]|[12]\d|30)/((19|[2-9]\d)\d{2}))|(02/(0[1-9]|1\d|2[0-8])/((19|[2-9]\d)\d{2}))|(02/29/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g

Sathish
  • 69
  • 1
  • 3
  • 7
  • 2
    Better try to construct Date object from the input string and if it is valid (not null), the date is valid. Because issues like leap year and number of days in a month will be solved easily – Vasilen Donchev Jul 06 '13 at 12:38
  • 3
    Using a regular expression is a bad idea here. People fail to get leap year calculations right at the best of times - trying to do it in a regex would be horrible. – Jon Skeet Jul 06 '13 at 12:38
  • Have a look at this answer to give you some alternative ideas: http://stackoverflow.com/a/16464768/592253 – Xotic750 Jul 06 '13 at 12:41
  • You should not be asking if someone can change your code for you! http://momentjs.com/ – iConnor Jul 06 '13 at 12:45
  • I need the above regular expression to be changed to mm/dd/yyyy format, because the javascript date function takes it in mm/dd/yyyy format – Sathish Jul 06 '13 at 12:47
  • 1
    Parse the string yourself and feed in the component parts, see [`String.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) and [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) – Xotic750 Jul 06 '13 at 12:51
  • There are lots of examples here on SO for dealing with conversion, here is another reference: http://stackoverflow.com/questions/17093796/date-formatting-with-without-moment-js/17094020#17094020 – Xotic750 Jul 06 '13 at 12:56
  • http://jsfiddle.net/LSsMc/ – Sathish Jul 06 '13 at 13:17
  • Here's another: [Test if date is Valid](http://stackoverflow.com/questions/5812220/test-if-date-is-valid/5812341#5812341). – RobG Jul 06 '13 at 22:45

1 Answers1

5

Try with

function validateDate(testdate) {
    var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
    return date_regex.test(testdate);
}

But better to use regular expression use Date object from your date string and then validate it.

GautamD31
  • 28,552
  • 10
  • 64
  • 85