I was looking for a simple Javascript function to check or validate a date string and most of the examples I have come across are too verbose. So I came up with a simple function that uses Regular Expressions and the built-in Date class.
//Checks if a given date string is in // one of the valid formats: // a) M/D/YYYY format // b) M-D-YYYY format // c) M.D.YYYY format // d) M_D_YYYY format function isDate(s) { // make sure it is in the expected format if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0) return false; // remove other separators that are not valid with the Date class s = s.replace(/[\-|\.|_]/g, "/"); // convert it into a date instance var dt = new Date(Date.parse(s)); // check the components of the date // since Date instance automatically rolls over each component var arrDateParts = s.split("/"); return ( dt.getMonth() == arrDateParts[0]-1 && dt.getDate() == arrDateParts[1] && dt.getFullYear() == arrDateParts[2] ); } // test function to test the isDate function function test_isDate() { var arrDates = [ '05/15/2008', '05-15-2008', '05.15.2008', '05_15_2008', '15/15/2008', '05/35/2008', '05/15/1908', '15-15-2008', 'a/1b/2008', '05/30/a008' ]; for (var d in arrDates) document.writeln("isDate('" + arrDates[d] + "') : " + isDate(arrDates[d]) + ""); }
By the way, I am using a Javascript utility called SyntaxHighlighter, to render this code. If you have not already used this utility, I would highly recommend you check it out.
The code is self explanatory and when you run the test function, you get the following results:
Happy coding,
Sonny
2 comments:
What if we want to change it to YYYY-MM-DD format?
I optimized the code a bit. First of all, you can move the regular expression to find [.-_] to the beginning to simply the following expressions. Second, this function will test for both 'Y/M/D' and 'M/D/Y'. Third, the returned value is a valid date if true.
top.isDate = function (s) {
s = s.replace(/[\-|\.\_]/g, '/');
s = s.replace(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/g , '$3/$1/$2');
if (s.search(/^\d{4}\/\d{1,2}\/\d{1,2}\b/g) != -1) {
var dt = new Date(Date.parse(s));
var arrDate = s.split("/");
if (dt.getMonth() == arrDate[1]-1 &&
dt.getDate() == arrDate[2] &&
dt.getFullYear() == arrDate[0]) {
var m = dt.getMonth() + 1;
var d = dt.getDate();
m = m < 10 ? '0' + m : m;
d = d < 10 ? '0' + d : d;
return arrDate[0] + '/' + m + '/' + d;
}
else {
return false;
}
} else {
return false;
}
}
Post a Comment