Edit: Now accepts a 100 year range up to this year.
Code JavaScript:
var formObj = (function(){
var dateRx = new RegExp("^(((\\d{4})(\\/)(0[13578]|10|12)(\\/)(0[1-9]|[12][0-9]|3[01]))|(\\d{4})"+
"(\\/)((0[469]|11)(\\/)([0][1-9]|[12][0-9]|30))|((\\d{4})(\\/)(02)(\\/)(0[1-9]|1[0-9]|2[0-8]))|"+
"(([02468][048]00)(\\/)(02)(\\/)(29))|(([13579][26]00)(\\/)(02)(\\/)(29))|(([0-9][0-9][0][48])"+
"(\\/)(02)(\\/)(29))|(([0-9][0-9][2468][048])(\\/)(02)(\\/)(29))|(([0-9][0-9][13579][26])(\\/)"+
"(02)(\\/)(29)))$");
var now = new Date(),
yrNow = now.getFullYear(), yrThen = yrNow - 100;
return {
isDate : function (input){
// match the first four digits and assign to yRx
var yRx = parseInt(input.match(/^\d{4}/));
// if yrx is valid, and in a range of the last 100 years then validate further
// returning true or false.
if (yRx && yRx < yrNow && yRx > yrThen){ return dateRx.test(input);}
// Otherwise the year has failed outright so return false
return false;
}
};
}());
Quick Tests
Code:
console.log(formObj.isDate("1980/02/29")); // true
console.log(formObj.isDate("1981/02/29")); // false
console.log(formObj.isDate("2009/04/31")); // false
console.log(formObj.isDate("2009/03/31")); // true
console.log(formObj.isDate("2007/43/31")); // false
console.log(formObj.isDate("1066/10/14")); // false
console.log(formObj.isDate("2200/09/12")); // false
RLM
Bookmarks