If we want to give a specific pattern to a date like DD/MM/YYYY or MM/DD/YYYY we can use this method.
var regex = /^(\d{1,2}-){2}\d{2}(\d{2})?$/;
console.log(regex.test('01-01-1990'));
// true
console.log(regex.test('01-01-90'));
// true
console.log(regex.test('01-01-190'));
// false
Let’s break that down and see what’s going on up there.
- Again, we have wrapped the entire regular expression inside
^and$, so that the match spans entire string. (start of first subexpression.\d{1,2}matches at least 1 digit and at most 2 digits.-matches the literal hyphen character.)end of first subexpression.{2}match the first subexpression exactly two times.\d{2}matches exactly two digits.(\d{2})?matches exactly two digits. But it’s optional, so either year contains 2 digits or 4 digits.