Regex for Date Validation in javascript

17,625

Solution 1

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
}

Solution 2

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

Solution 3

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
Share:
17,625
User_MVC
Author by

User_MVC

web developer.

Updated on July 28, 2022

Comments

  • User_MVC
    User_MVC almost 2 years

    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
    Mr_Green almost 11 years
    parseInt(match[0], 10) is the correct syntax.
  • Anirudha
    Anirudha almost 11 years
    @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..
  • Mr_Green
    Mr_Green almost 11 years
    Even Ecmascript 5 recommends radix.