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 开发者_StackOverflow社区= new RegExp("^\d{4}-\d{2}-\d{2}$");
if (pattern.test(date))
return true;
return false;
}
thanks!
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
- make leading zeroes optional (i. e. use
\d{1,2}
instead of\d{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.
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
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
精彩评论