2

pls can somebody give the date validation regex, which will allow the following rules are

  1. It should allow mm/dd/yyyy, m/d/yyyy, mm/d/yyyy, m/d/yyyy (not allow yy)
  2. Number of days for month (30 and 31) validation.
  3. Feb month validation for leap & non leap years.
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
User_MVC
  • 251
  • 2
  • 7
  • 21
  • 1
    `[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}` or see http://stackoverflow.com/questions/5465375/javascript-date-regex-dd-mm-yyyy – SpYk3HH May 09 '13 at 13:06
  • 2
    @MarioDeSchaepmeester: please [do not post](http://meta.stackexchange.com/questions/15650/ban-lmgtfy-let-me-google-that-for-you-links) LMGTFY links. – georg May 09 '13 at 13:19
  • 1
    @thg435 It's the first time I've ever done so, don't worry I'm not planning to do this more. This question just asked for it.. – MarioDS May 09 '13 at 13:24
  • 1
    @MarioDeSchaepmeester Before giving those type of comments, pls think once, who know's how to use Stack Overflow,they don't know how to use google... – User_MVC May 09 '13 at 19:18

3 Answers3

3

Don't try to parse date entirely with regex!Follow KISS principle..

1>Get the dates with this regex

^(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})$

2> Validate month,year,day if the string matches with above regex!

var match = myRegexp.exec(myString);
parseInt(match[0],10);//month
parseInt(match[1],10);//day
parseInt(match[2],10);//year
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • `parseInt(match[0], 10)` is the [**correct syntax**](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt#Octal_Interpretations_with_No_Radix). – Mr_Green May 09 '13 at 13:33
  • @Mr_Green yes..you are right specially in case if the digits start with `0` but this feature has been deprecated so anyway it would be base 10.. – Anirudha May 09 '13 at 13:35
  • Even Ecmascript 5 recommends [radix](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt#ECMAScript_5_Removes_Octal_Interpretation). – Mr_Green May 09 '13 at 13:42
2

Try this:

([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2}) 

and then if you got a valid string from the above regex then with string manipulations, do something like below:

if(/([0-9][1-2])\/([0-2][0-9]|[3][0-1])\/((19|20)[0-9]{2})/.test(text)){
    var tokens = text.split('/');  //  text.split('\/');
    var day    = parseInt(tokens[0], 10);
    var month  = parseInt(tokens[1], 10);
    var year   = parseInt(tokens[2], 10);
}
else{
    //show error
    //Invalid date format
}
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
1

Here's a full validation routine

var myInput = s="5/9/2013";
var r = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
if(!r.test(myInput)) {
  alert("Invalid Input");
  return;
}
var a = s.match(r), d = new Date(a[3],a[1] - 1,a[2]);
if(d.getFullYear() != a[3] || d.getMonth() + 1 != a[1] || d.getDate() != a[2]) {
  alert("Invalid Date");
  return;
}

// process valid date
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53