Date and Time Validations

Comparing dates in validation logic

Overview

In these examples, the rules are comparing and validating date selector fields, both with and without the time component.

These rules run on the submit event and general you will want to run validation logic on submit so that if the validation fails, the form will not submit.

Comparing Dates

In this example, the logic ensures that the trip start date is on or after the current date and the end date is after the start. The date selector fields are dates only (no time).

// Ensure trip start is today or later and trip end is after start

// get today's date
const today = new Date(new Date().toISOString().slice(0,10));

// make sure and trip-start-date is >= today
if (TripStartDate.value && TripEndDate.value) {
  const tripStartDate = new Date(TripStartDate.value);
  const tripEndDate = new Date(TripEndDate.value);
  
  if (tripStartDate.getTime() < today.getTime()) {
    // The date is earlier than today, so set a validation error on the trip-start-date field
    TripStartDate.setError('Start date must be on or after today');
  }
  if (tripEndDate.getTime() <= tripStartDate.getTime()) {
    // The end date is not after start, so set a validation error on the trip-end-date field
    TripEndDate.setError('End date must be on or after Start Date');
  }
}

Comparing Dates with a Time part

In this example, the logic ensures that the help request response date and time is after the help request date and time. The date selector fields are dates with a time part.

Last updated

Was this helpful?