"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What Regular Expression Validates DD/MM/YYYY Dates for Spanish Usage in JavaScript?

What Regular Expression Validates DD/MM/YYYY Dates for Spanish Usage in JavaScript?

Published on 2024-11-03
Browse:963

What Regular Expression Validates DD/MM/YYYY Dates for Spanish Usage in JavaScript?

Date Format Validation in Javascript with Regular Expressions: Focusing on DD/MM/YYYY

Matching dates in a specific format is crucial for data validation in javascript. While a regex exists for the YYYY-MM-DD format, the need arises for a pattern to validate dates in DD/MM/YYYY format, with a focus on Spanish usage and the exclusion of slashes or dashes as separators.

To address this requirement, a regex that flips the order of the day, month, and year components can be employed:

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

This revised regex allows for the validation of dates in either DD/MM/YYYY or DD-MM-YYYY format. It restricts the separators to periods (.) and hyphens (-) while preventing the use of slashes (/).

To implement this regex in a javascript validation context, the following adjustments can be made:

[...]
"date": {
    "regex": /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/,
    "alertText": "Alert text DD/MM/YYYY"
},
"other type..."[...]

With this modified regex, dates in the DD/MM/YYYY format can be validated, ensuring the correct format for Spanish usage and excluding invalid dates such as 31/02/4899.

Release Statement This article is reprinted at: 1729406296 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3