gsquare567
gsquare567

Reputation: 2947

Javascript Date Regex eg. 2010-06-03

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!

Upvotes: 1

Views: 126

Answers (3)

macf00bar
macf00bar

Reputation: 700

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

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

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.

Upvotes: 4

jantimon
jantimon

Reputation: 38160

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

Upvotes: 0

Related Questions