How to Validate From and To Dates Using Date.parse in JavaScript?

Estimated read time 1 min read

In JavaScript, you can validate “from” and “to” dates using the Date.parse() method.

Here is an example of how to validate the “from” and “to” dates using Date.parse():

// Get the "from" and "to" dates from the form inputs
const fromDateString = document.getElementById('from-date-input').value;
const toDateString = document.getElementById('to-date-input').value;

// Parse the "from" and "to" dates using Date.parse()
const fromDate = Date.parse(fromDateString);
const toDate = Date.parse(toDateString);

// Check if the parsed dates are valid
if (isNaN(fromDate) || isNaN(toDate)) {
  // Handle invalid date input
  console.log('Invalid date input!');
} else if (fromDate > toDate) {
  // Handle invalid date range
  console.log('"From" date must be before "to" date!');
} else {
  // Valid date range
  console.log('Valid date range!');

In this example, we first get the “from” and “to” dates from the form inputs. Then, we parse the dates using Date.parse(). If either of the parsed dates is NaN, we handle the invalid date input. Otherwise, we compare the parsed dates to ensure that the “from” date is before the “to” date. If the date range is valid, we can proceed with the rest of the logic.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply