Reputation: 261
pls can somebody give the date validation regex, which will allow the following rules are
Upvotes: 2
Views: 19050
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
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
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