views:

335

answers:

2

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?

+5  A: 

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)

Jeff
I don't want to add an answer since this one is right, but I will point out for Ian's sake that the pattern is pretty liberal as it is right now. For instance under the current pattern "1991-50-42" would pass as a valid date.
EBGreen
Yes, there is other code i didnt show for aesthetic reasons that checks each element in matches.
Ian McCullough
Why not just have the regex pattern at least make sure that the string *could* be a date?
EBGreen
i never thought about doing it like that. How would i do it?
Ian McCullough
Well Peter's answer is good. I can't test it right now, but I think a pattern like: '^\\d{4}[\\/-]1*[012][\\/-][0123]*\d$'
EBGreen
EBGreen: * is zero or more matches. So 1999-110-229 would match. Just use ? instead.
Jeff
+4  A: 

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

Peter Bailey