Home > Web Front-end > JS Tutorial > How to Reliably Validate Dates in \'mm/dd/yyyy\' Format in JavaScript?

How to Reliably Validate Dates in \'mm/dd/yyyy\' Format in JavaScript?

Patricia Arquette
Release: 2024-11-01 19:49:02
Original
937 people have browsed it

How to Reliably Validate Dates in

Validating Dates in "mm/dd/yyyy" Format in JavaScript

When attempting to validate dates in the format "mm/dd/yyyy" using the provided code, you might encounter issues. Let's analyze the possible errors and provide a more reliable solution.

The original function checks if the input string matches the desired format and attempts to create a Date object from the provided values. However, there might be discrepancies between the input date and the calculated parts from the Date object, leading to incorrect validation.

Improved Validation Function

To address this, a more robust validation function can be utilized:

<code class="javascript">function isValidDate(dateString) {
  // Validate Format
  if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) return false;

  // Parse Date Components
  const parts = dateString.split("/");
  const day = parseInt(parts[1], 10);
  const month = parseInt(parts[0], 10);
  const year = parseInt(parts[2], 10);

  // Check Range of Month and Year
  if (year < 1000 || year > 3000 || month < 1 || month > 12) return false;

  // Adjust for Leap Years
  const monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if ((year % 400 === 0) || ((year % 100 !== 0) && (year % 4 === 0))) {
    monthLength[1] = 29;
  }

  // Check Valid Day Range
  return day > 0 && day <= monthLength[month - 1];
}</code>
Copy after login

This function thoroughly validates date strings by checking the format, parsing individual components, evaluating the validity of month and year ranges, and factoring in leap years to determine the valid range of days.

The above is the detailed content of How to Reliably Validate Dates in \'mm/dd/yyyy\' Format in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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