Home > Web Front-end > JS Tutorial > body text

How to Validate Dates in DD/MM/YYYY Format using Regular Expressions in JavaScript?

Patricia Arquette
Release: 2024-10-20 14:48:30
Original
961 people have browsed it

How to Validate Dates in DD/MM/YYYY Format using Regular Expressions in JavaScript?

Matching Dates in DD/MM/YYYY Format with Regular Expressions

In Javascript, validating dates in various formats is a common task. Among them, the DD/MM/YYYY (day-month-year) pattern is often encountered.

One may initially consider adapting a YYYY-MM-DD regex to this format. However, a more straightforward approach is to rearrange the expression:

^(0?[1-9]|[12][0-9]|3[01])[\/\-]\/(0?[1-9]|1[012])[\/\-]\d{4}$
Copy after login

This regex captures dates in the DD/MM/YYYY format, accepting either "/" or "-" as the separator. However, it also allows invalid dates such as 31/02/4899.

To escape slashes in the regex, use the backslash () character:

^\(0?[1-9]|[12][0-9]|3[01])[\/\-]\/(0?[1-9]|1[012])[\/\-]\d{4}$
Copy after login

Alternatively, you can enclose the slash in square brackets:

^(\[\/\]0?[1-9]|[12][0-9]|3[01])[\/-](0?[1-9]|1[012])[\/-]\d{4}$
Copy after login

Both methods ensure the slash is treated as a literal character within the regex. When placing the regex in a .js file, the appropriate escaping method depends on the way the string is defined:

  • For double-quoted strings ("string"), use /: ".*/ 0?[1-9]..."
  • For single-quoted strings ('string'), use /: '.*/ 0?[1-9]...'

The above is the detailed content of How to Validate Dates in DD/MM/YYYY Format using Regular Expressions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!