Why not just skip regex altogether here? I know this is way more code, but it will give errors for dates that a regex can't, like a date specifying November 31st.
var datesToTest = [
"1991-12-01" // valid
, "1991-11-31" // invalid, Nov has 30 days
, "1991-13-01" // invalid, no 13th month
];
// Note: console.log() requires Firebug - switch to alert() if you wish
for ( var i = 0; i < datesToTest.length; i++ )
{
if ( !isValidDate( datesToTest[i], '-' ) )
{
console.log( datesToTest[i] + ' is not a valid date!' );
} else {
console.log( datesToTest[i] + ' is valid date!' );
}
}
function isValidDate( dateAsString, delimiter )
{
var dateObject = new Date( dateAsString.replace( new RegExp( delimiter, 'g' ), '/' ) );
var checkDate = [
dateObject.getFullYear()
, zeroFill( dateObject.getMonth() + 1, 2 )
, zeroFill( dateObject.getDate(), 2 )
].join( delimiter );
return ( dateAsString == checkDate );
}
function zeroFill( number, width )
{
width -= number.toString().length;
if ( width > 0 )
{
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number;
}
This will work as long as you don't need to validate a date before 100 AD =P