Home > Web Front-end > JS Tutorial > How Can I Efficiently Validate User-Entered Dates in JavaScript?

How Can I Efficiently Validate User-Entered Dates in JavaScript?

DDD
Release: 2024-11-30 20:05:20
Original
857 people have browsed it

How Can I Efficiently Validate User-Entered Dates in JavaScript?

Validating Dates

When conducting user input validation, it's essential to ensure that dates entered are valid. For instance, a date like "2/30/2011" should be identified as incorrect.

A simple yet effective method to validate dates is to convert the input string into a date object and check its validity. As demonstrated in the code snippet below, it creates a date object from the input string and compares its month to the expected month based on the string. If they match, the date is considered valid.

// Expect input as d/m/y
function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d && (d.getMonth() + 1) == bits[1];
}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
  console.log(s + ' : ' + isValidDate(s))
})
Copy after login

This method provides a straightforward approach to validate dates, ensuring that invalid inputs are identified and rejected.

The above is the detailed content of How Can I Efficiently Validate User-Entered Dates 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template