views:

51

answers:

3

i want a function that validates dates of the format in the title. what is wrong with my function?

function validateDate(date) {
 var pattern = new RegExp("^\d{4}-\d{2}-\d{2}$");
 if (pattern.test(date))
  return true;
 return false;
}

thanks!

+4  A: 

You either need to use a regex object: /^\d{4}-\d{2}-\d{2}$/ or escape the backslashes: "^\\d{4}-\\d{2}-\\d{2}$".

Also, this regex will fail if there is anything else in the string besides the date (for example whitespace).

So

var pattern = /^\s*\d{4}-\d{2}-\d{2}\s*$/;

might be a better bet.

This regex will (of course) not check for valid dates, only for strings that consist of four digits, a hyphen, two digits, another hyphen, and two more digits. You might want to

  1. make leading zeroes optional (i. e. use \d{1,2} instead of \d{2})
  2. perform an actual date validation outside of the regex.

You can (sort of) validate dates by using regexes, but they are not pretty. Even worse if you want to account for leap years or restrict a date range.

Tim Pietzcker
thanks! you also cleared up my confusion about the /REGEX/ notation. i tried that but had it in quotes, not knowing that it automagically creates a regex object =D
gsquare567
A: 

This works however it will validate dates like 9999-99-99.

function validateDate( date )
{
  return /^\d{4}\-\d{2}\-\d{2}$/.test( date )
}

console.log( validateDate ( '2010-01-01' ) ); // True
Ghommey
A: 

hi!

that's what you can come up with with some help from RegexBuddy (untested by myself):

function validateDate(date) {
var pattern = new RegExp("(19|20)[0-9]{2}[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])");
var match = pattern.exec(date);
if (match != null) {
    return true;
} else {
   return false;    
}

}

--Reinhard

pastacool