How to give a specific format pattern for a date (DD/MM/YY OR MM/DD/YYYY) in JavaScript

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.

  1. Again, we have wrapped the entire regular expression inside and $, so that the match spans entire string.
  2. ( start of first subexpression.
  3. \d{1,2} matches at least 1 digit and at most 2 digits.
  4. - matches the literal hyphen character.
  5. ) end of first subexpression.
  6. {2} match the first subexpression exactly two times.
  7. \d{2} matches exactly two digits.
  8. (\d{2})? matches exactly two digits. But it’s optional, so either year contains 2 digits or 4 digits.

Leave a comment

Your email address will not be published. Required fields are marked *