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}$
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}$
Alternatively, you can enclose the slash in square brackets:
^(\[\/\]0?[1-9]|[12][0-9]|3[01])[\/-](0?[1-9]|1[012])[\/-]\d{4}$
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:
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!