I am creating a date validation in Javascript with regex. In some cases it is not working
'(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.][0-9]{4})'
11/11/1000 - Correct
11/11/0000 - INVALID
Zero should not be allowed in year
I am creating a date validation in Javascript with regex. In some cases it is not working
'(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.][0-9]{4})'
11/11/1000 - Correct
11/11/0000 - INVALID
Zero should not be allowed in year
You should avoid using a regular expression to validate dates. Parse the date string as an actual date and check to see if it is actually valid.
Note: The usage of +token[n]
and parseInt(token[n], 10)
below are interchangeable.
const validateDate = (dateString) => {
const tokens = dateString.split('/');
// Must be 3 tokens
if (tokens.length !== 3) return false;
// Must all be numeric
if (tokens.some(token => isNaN(parseInt(token, 10)))) return false;
// Year must !== 0
if (+tokens[2] === 0) return false;
const date = new Date(+tokens[2], +tokens[0] - 1, +tokens[1]);
// Must be a valid date
return date instanceof Date && !isNaN(date);
};
console.log(validateDate('11/11/1000')); // true
console.log(validateDate('11/11/0000')); // false
Here is an alternate version that is slightly optimized.
const validateDate = (dateString) => {
const [month, date, year] = dateString.split('/').map(token => +token);
if (year === 0 || isNaN(year) || isNaN(month) || isNaN(date)) return false;
const dateObj = new Date(year, month - 1, date);
return dateObj instanceof Date && !isNaN(dateObj);
};
console.log(validateDate('11/11/1000')); // true
console.log(validateDate('11/11/0000')); // false