"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 > How to Validate Dates in DD/MM/YYYY Format Using JavaScript Regular Expression?

How to Validate Dates in DD/MM/YYYY Format Using JavaScript Regular Expression?

Published on 2024-11-06
Browse:485

How to Validate Dates in DD/MM/YYYY Format Using JavaScript Regular Expression?

Validating Dates in DD/MM/YYYY Format Using JavaScript Regular Expression

Validating dates is a common task in programming, and the ability to ensure a date is in a specific format is crucial. In JavaScript, regular expressions provide a powerful tool for performing such validations.

Consider the regex pattern for validating dates in YYYY-MM-DD format:

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

To adapt this pattern for DD/MM/YYYY, we simply need to flip the group positions for day and year:

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

This updated pattern will validate dates in DD/MM/YYYY format. Additionally, it includes the following considerations:

  • Accepts either "/" or "-" as a separator
  • Allows days from 1 to 31
  • Allows months from 1 to 12
  • Validates years from 1900 onwards

To use this pattern in JavaScript, you can assign it to a variable and utilize the test() method to validate a date string:

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

const dateString = '12/03/2022';

console.log(dateRegEx.test(dateString)); // Output: true

By leveraging this regular expression, you can ensure the validity of dates in DD/MM/YYYY format, ensuring the accuracy and reliability of your data processing algorithms.

Release Statement This article is reprinted at: 1729406719 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