Home  >  Article  >  Web Front-end  >  Is This the Correct Regex for Validating Dates in DD/MM/YYYY Format?

Is This the Correct Regex for Validating Dates in DD/MM/YYYY Format?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 14:42:29305browse

Is This the Correct Regex for Validating Dates in DD/MM/YYYY Format?

Javascript Regex for Validating Dates in DD/MM/YYYY Format

In this post, we'll explore the regex pattern for validating dates in the DD/MM/YYYY format, specifically for a Spanish-language setting.

The Correct Regex Pattern

The provided regex string, (0[1-9]|[12][0-9]|3[01])[ .-](0[1-9]|1[012])[ .-](19|20|)dd, does not correctly validate dates in DD/MM/YYYY format.

The correct regex pattern for this format is:

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

This pattern flips the day and month components compared to the original YYYY-MM-DD pattern. It also specifies that only the forward slash (/) or hyphen (-) should be used as separators.

Escaping the Slashes

When using the regex pattern in JavaScript code, you need to escape the forward slashes to prevent them from being interpreted as line breaks. This can be done by adding a backslash () before each slash:

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

Example Usage

The following JavaScript code demonstrates how to use the regular expression to validate a date in DD/MM/YYYY format:

const testDate = "15/05/2023";
const isValid = testDate.match(regex);

if (isValid) {
  console.log("Valid date.");
} else {
  console.log("Invalid date.");
}

This code would output "Valid date." because "15/05/2023" is a valid date in the DD/MM/YYYY format.

The above is the detailed content of Is This the Correct Regex for Validating Dates in DD/MM/YYYY Format?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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