Edit: exact solution below
You could do something like this, but with a more accurate algorithm for day validation:
function testDate(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if(t === null)
return false;
var d = +t[1], m = +t[2], y = +t[3];
// Below should be a more acurate algorithm
if(m >= 1 && m <= 12 && d >= 1 && d <= 31) {
return true;
}
return false;
}
http://jsfiddle.net/aMWtj/
Date validation alg.: http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf
Exact solution: function that returns a parsed date or null, depending exactly on your requirements.
function parseDate(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if(t !== null){
var d = +t[1], m = +t[2], y = +t[3];
var date = new Date(y, m - 1, d);
if(date.getFullYear() === y && date.getMonth() === m - 1) {
return date;
}
}
return null;
}
http://jsfiddle.net/aMWtj/2/
In case you need the function to return true/false and for a yyyy/mm/dd format
function IsValidDate(pText) {
var isValid = false ;
var t = pText.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
if (t !== null) {
var y = +t[1], m = +t[2], d = +t[3];
var date = new Date(y, m - 1, d);
isValid = (date.getFullYear() === y && date.getMonth() === m - 1) ;
}
return isValid ;
}
parseInt
. I.e.,d=+t[1]
. Avoids problems like where you forgot to include the radix on the day calculation (particularly problematic when we know the day may have leading zeros). – Pricket