To validate a date in JavaScript, use the regular expression pattern, that ensures
dd/mm/yy
or mm/dd/yy
format.Here's how you do it:
const ddmmyy = /^(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[0-2])\/(0[1-9]|1[1-9]|2[1-9])$/;
console.log(ddmmyy.test('30/08/22')); // true
console.log(ddmmyy.test('42/08/22')); // false
console.log(ddmmyy.test('Hello World!')); // false
const mmddyy = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[1-9]|2[1-9])$/;
console.log(mmddyy.test('08/30/22')); // true
console.log(mmddyy.test('08/42/22')); // false
console.log(ddmmyy.test('Hello World!')); // false