简体   繁体   中英

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: function(value, element) {
    if (this.optional(element)) return true;
    var regexp = new RegExp('^\d{4}[\/-](\d{1,2})[\/-](\d{1,2})$');
    var matches = regexp.exec(value);
    alert(matches);

Any ideas?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM