JavaScript Answers

How to Validate if a Date with Format MM/DD/YYYY in JavaScript?

Spread the love

We check if a date has the MM/DD/YYYY format with JavaScript with the test method.

For instance, we can write:

const dateRegex = /^(0\[1-9]|1\[0-2\])\/(0\[1-9]|1\d|2\\d|3\[01])\/(19|20)\d{2}$/;

We have the dateRegex regex that checks if a string is in the MM/DD/YYYY format.

The pattern (0[1–9]|1[0–2]) checks if the first number is between 01 and 12.

The pattern (0[1–9]|1\d|2\d|3[01]) checks if the second number is between 01 and 31.

And (19|20)\d{2} checks if the 3rd number starts with 19 or 20 and ends with 2 digits.

\/ checks whether slashes are between the numbers.

Therefore, the first console log is false and the 2nd one logs true .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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