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

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

Mary-Kate Olsen
Release: 2024-10-20 14:47:02
Original
424 people have browsed it

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])$/
Copy after login

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}$
Copy after login

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
Copy after login

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.

The above is the detailed content of How to Validate Dates in DD/MM/YYYY Format Using JavaScript Regular Expression?. 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!