User_MVC
User_MVC

Reputation: 261

Regex for Date Validation in javascript

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.

Upvotes: 2

Views: 19050

Answers (3)

Anirudha
Anirudha

Reputation: 32797

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

Upvotes: 3

Mr_Green
Mr_Green

Reputation: 41832

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
}

Upvotes: 2

ic3b3rg
ic3b3rg

Reputation: 14927

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

Upvotes: 1

Related Questions