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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
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
\d{1,2}instead of\d{2})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.