Whats Wrong With This JQuery Validation Code? Regexp.exec(value)
Value will be anything and matches is null. The point of this is to split up a string like '1991-12-01' and make sure that all of the parts of the string are valid dates. dateISO:
Solution 1:
The expression you're giving is a string, thus, needs escaping:
var regexp = new RegExp('^\\d{4}[\\/-](\\d{1,2})[\\/-](\\d{1,2})$');
Alternatively, you can do the perl-styled expressions, but slashes need to be escaped:
var regexp = /^\d{4}[\\/-](\d{1,2})[\\/-](\d{1,2})$/;
(The perl-styled regular expression returns a RegExp object)
Solution 2:
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
Post a Comment for "Whats Wrong With This JQuery Validation Code? Regexp.exec(value)"