Component Library

← Back to gallery

Date range order validation in HTML, CSS and vanilla JS

A copy-paste Date range order validation in plain HTML and CSS, with vanilla JavaScript: no framework, no build step, MIT-licensed.

Category: Forms · Tags: date, validation, error, live region, form

Live preview

Source (copy-ready)

<section class="example-date-range-validation" data-dcl-scheme="light" aria-labelledby="example-date-range-validation-title">
<header><h2 id="example-date-range-validation-title">Date range order validation</h2>
<p>An end before the start is rejected inline and announced as soon as the pair is complete.</p></header>
<div class="parts">
<form data-form novalidate>
  <fieldset>
    <legend>Project dates</legend>
    <div class="two-column">
      <div class="field"><label for="example-date-range-validation-start">Start date</label><input type="date" id="example-date-range-validation-start" aria-describedby="example-date-range-validation-error" required data-start></div>
      <div class="field"><label for="example-date-range-validation-end">End date</label><input type="date" id="example-date-range-validation-end" aria-describedby="example-date-range-validation-error" required data-end></div>
    </div>
  </fieldset>
  <div class="error-box" id="example-date-range-validation-error" data-error hidden>The end date must be the same as or after the start date.</div>
  <div class="actions"><button type="submit">Apply dates</button></div>
</form>
<p class="status" role="status" aria-live="polite" data-status></p>
</div>
<script>
(() => {
  const root = document.currentScript.closest(".example-date-range-validation");
  const instance = Array.from(document.getElementsByClassName("example-date-range-validation")).indexOf(root);
  if (instance > 0) {
    const singleReferences = ["id", "aria-activedescendant", "for", "list", "name"];
    const tokenReferences = ["aria-labelledby", "aria-controls", "aria-describedby"];
    for (const element of [root, ...root.querySelectorAll("*")]) {
      for (const attr of singleReferences) {
        if (element.hasAttribute(attr)) element.setAttribute(attr, element.getAttribute(attr) + "--" + instance);
      }
      for (const attr of tokenReferences) {
        if (element.hasAttribute(attr)) {
          const rewritten = element.getAttribute(attr).trim().split(/\s+/).filter(Boolean).map((reference) => reference + "--" + instance);
          element.setAttribute(attr, rewritten.join(" "));
        }
      }
      const href = element.getAttribute("href");
      if (href && href.startsWith("#")) element.setAttribute("href", href + "--" + instance);
    }
  }
  const preference = matchMedia("(prefers-color-scheme: dark)");
  const apply = () => { root.dataset.dclScheme = preference.matches ? "dark" : "light"; };
  preference.addEventListener("change", apply);
  apply();
  const form = root.querySelector("[data-form]");
  const start = root.querySelector("[data-start]");
  const end = root.querySelector("[data-end]");
  const error = root.querySelector("[data-error]");
  const status = root.querySelector("[data-status]");
  function dayNumber(input) {
    if (!input.value) return null;
    const parts = input.value.split("-").map(Number);
    return Date.UTC(parts[0], parts[1] - 1, parts[2]) / 86400000;
  }
  function validate() {
    const first = dayNumber(start);
    const last = dayNumber(end);
    const invalid = first !== null && last !== null && last < first;
    error.hidden = !invalid;
    start.setAttribute("aria-invalid", String(invalid));
    end.setAttribute("aria-invalid", String(invalid));
    if (!invalid && first !== null && last !== null) status.textContent = "Date order is valid.";
    return !invalid;
  }
  start.addEventListener("input", validate);
  end.addEventListener("input", validate);
  function submitForm() {
    const missing = [start, end].find((input) => !input.value);
    if (missing) {
      missing.reportValidity();
      missing.focus();
      return;
    }
    if (validate()) status.textContent = "Dates applied in this example; no data left the page.";
  }
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    submitForm();
  });
  const submitButton = form.querySelector('button[type="submit"]');
  if (submitButton) {
    submitButton.addEventListener("click", (event) => {
      event.preventDefault();
      submitForm();
    });
  }
  form.addEventListener("keydown", (event) => {
    if (event.key !== "Enter" || event.defaultPrevented) return;
    if (!event.target.matches("input, select")) return;
    event.preventDefault();
    submitForm();
  });
})();
</script></section>
<style>
.example-date-range-validation { color: #11292f; background-color: #ffffff; color-scheme: light; }
.example-date-range-validation a { color: #005c62; }
.example-date-range-validation button, .example-date-range-validation summary, .example-date-range-validation input, .example-date-range-validation select, .example-date-range-validation textarea {
  color: #11292f; background-color: #e4edef; border-color: #697f84;
}
.example-date-range-validation button:hover, .example-date-range-validation summary:hover, .example-date-range-validation button[aria-selected="true"], .example-date-range-validation button[aria-pressed="true"] {
  color: #ffffff; background-color: #00535a;
}
.example-date-range-validation dialog { color: #11292f; background-color: #ffffff; }
.example-date-range-validation [data-note] { color: #11292f; background-color: #e4edef; }
.example-date-range-validation [data-error] { color: #7f1d1d; background-color: #fee2e2; }
.example-date-range-validation [data-success] { color: #14532d; background-color: #dcfce7; }
.example-date-range-validation [data-warning] { color: #713f12; background-color: #fef9c3; }
.example-date-range-validation :focus-visible { outline: 3px solid #005c62; outline-offset: 2px; }

.example-date-range-validation[data-dcl-scheme="dark"] { color: #eff8f9; background-color: #142f36; color-scheme: dark; }
.example-date-range-validation[data-dcl-scheme="dark"] a { color: #8fe1da; }
.example-date-range-validation[data-dcl-scheme="dark"] button, .example-date-range-validation[data-dcl-scheme="dark"] summary,
.example-date-range-validation[data-dcl-scheme="dark"] input, .example-date-range-validation[data-dcl-scheme="dark"] select, .example-date-range-validation[data-dcl-scheme="dark"] textarea {
  color: #eff8f9; background-color: #1c3c44; border-color: #839fa5;
}
.example-date-range-validation[data-dcl-scheme="dark"] button:hover, .example-date-range-validation[data-dcl-scheme="dark"] summary:hover,
.example-date-range-validation[data-dcl-scheme="dark"] button[aria-selected="true"], .example-date-range-validation[data-dcl-scheme="dark"] button[aria-pressed="true"] {
  color: #11292f; background-color: #8fe1da;
}
.example-date-range-validation[data-dcl-scheme="dark"] dialog { color: #eff8f9; background-color: #142f36; }
.example-date-range-validation[data-dcl-scheme="dark"] [data-note] { color: #eff8f9; background-color: #1c3c44; }
.example-date-range-validation[data-dcl-scheme="dark"] [data-error] { color: #fecaca; background-color: #451a1a; }
.example-date-range-validation[data-dcl-scheme="dark"] [data-success] { color: #bbf7d0; background-color: #14532d; }
.example-date-range-validation[data-dcl-scheme="dark"] [data-warning] { color: #fde68a; background-color: #451a03; }
.example-date-range-validation[data-dcl-scheme="dark"] :focus-visible { outline: 3px solid #8fe1da; outline-offset: 2px; }

.example-date-range-validation, .example-date-range-validation * { box-sizing: border-box; min-width: 0; }
.example-date-range-validation { display: block; font: 1rem/1.5 system-ui, sans-serif; padding: 1rem; border-radius: 0.75rem; overflow-wrap: anywhere; }
.example-date-range-validation h2, .example-date-range-validation h3 { line-height: 1.15; margin-block: 0 0.75rem; }
.example-date-range-validation header p, .example-date-range-validation p { margin-block: 0.5rem; }
.example-date-range-validation ul, .example-date-range-validation ol { margin-block: 0.5rem; padding-inline-start: 1.5rem; }
.example-date-range-validation dl { margin-block: 0.5rem; }
.example-date-range-validation dt { font-weight: 700; }
.example-date-range-validation dd { margin: 0 0 0.6rem; }
.example-date-range-validation fieldset { min-inline-size: 0; margin: 0; border: 1px solid; border-radius: 0.5rem; padding: 0.75rem; }
.example-date-range-validation legend { padding-inline: 0.25rem; font-weight: 700; }
.example-date-range-validation button, .example-date-range-validation input, .example-date-range-validation select, .example-date-range-validation textarea {
  min-block-size: 44px; border: 1px solid; border-radius: 0.375rem; padding: 0.5rem 0.75rem; font: inherit;
}
.example-date-range-validation input, .example-date-range-validation select, .example-date-range-validation textarea { display: block; inline-size: 100%; max-inline-size: 100%; }
.example-date-range-validation input[type="checkbox"], .example-date-range-validation input[type="radio"] {
  display: inline-block; inline-size: auto; min-block-size: auto; padding: 0; flex: 0 0 auto;
}
.example-date-range-validation input[type="file"] { padding: 0.45rem; }
.example-date-range-validation input[type="range"] { padding-inline: 0; }
.example-date-range-validation textarea { min-block-size: 6rem; resize: vertical; }
.example-date-range-validation button, .example-date-range-validation summary { cursor: pointer; transition: background-color 140ms ease-out; }
.example-date-range-validation button:disabled { cursor: not-allowed; text-decoration: line-through; }
.example-date-range-validation table { border-collapse: collapse; inline-size: 100%; }
.example-date-range-validation th, .example-date-range-validation td { padding: 0.5rem; text-align: start; border-block-end: 1px solid; }
.example-date-range-validation [hidden] { display: none !important; }
.example-date-range-validation [data-note], .example-date-range-validation [data-error], .example-date-range-validation [data-success], .example-date-range-validation [data-warning] { border-radius: 0.5rem; padding: 0.65rem; }
.example-date-range-validation .parts { display: grid; gap: 1rem; }
.example-date-range-validation .field, .example-date-range-validation .fields { display: grid; gap: 0.4rem; }
.example-date-range-validation .fields { gap: 0.75rem; }
.example-date-range-validation .actions, .example-date-range-validation .inline-row { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }
.example-date-range-validation .panel { border: 1px solid; border-radius: 0.5rem; padding: 0.75rem; }
.example-date-range-validation .plain-list { margin: 0; padding: 0; list-style: none; }
.example-date-range-validation .choice { display: flex; gap: 0.5rem; align-items: flex-start; }
.example-date-range-validation .choice input { margin-block-start: 0.25rem; }
.example-date-range-validation .choice-stack { display: grid; gap: 0.55rem; }
.example-date-range-validation .tile { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0.55rem; align-items: start; border: 1px solid; border-radius: 0.5rem; padding: 0.75rem; }
.example-date-range-validation .tile[data-active] { border-width: 3px; padding: calc(0.75rem - 2px); }
.example-date-range-validation .pill { display: inline-flex; gap: 0.4rem; align-items: center; border: 1px solid; border-radius: 999px; padding: 0.35rem 0.7rem; }
.example-date-range-validation .pill[data-active] { border-width: 3px; padding: calc(0.35rem - 2px) calc(0.7rem - 2px); }
.example-date-range-validation .hint { font-size: 0.875rem; }
.example-date-range-validation .status { min-block-size: 1.5rem; margin-block: 0; }
.example-date-range-validation .two-column, .example-date-range-validation .split-layout { display: grid; gap: 1rem; }
.example-date-range-validation .sticky-panel { position: sticky; inset-block-start: 1rem; align-self: start; }
.example-date-range-validation .scroll-x { overflow-x: auto; max-inline-size: 100%; }
.example-date-range-validation .visually-hidden {
  position: absolute; inline-size: 1px; block-size: 1px; padding: 0; margin: -1px;
  overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
}
@media (min-width: 34rem) {
  .example-date-range-validation .two-column { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .example-date-range-validation .split-layout { grid-template-columns: minmax(0, 1fr) minmax(12rem, 18rem); }
}
@media (max-width: 30rem) {
  .example-date-range-validation { padding: 0.75rem; }
  .example-date-range-validation .actions, .example-date-range-validation .inline-row { align-items: stretch; }
  .example-date-range-validation .wizard-steps { grid-template-columns: minmax(0, 1fr) !important; }
}
@media (prefers-reduced-motion: reduce) { .example-date-range-validation * { transition: none !important; } }
.example-date-range-validation .error-box[hidden] { display: none !important; }

.example-date-range-validation form { display: grid; gap: 0.75rem; }
.example-date-range-validation .error-box { display: block; }
</style>

When to use

Use this where either date can be edited independently and order validation must happen before submission. Keep the message specific rather than relying on the browser's generic date validation.

Avoid

Do not validate only on blur or only at the server; people should learn about the inverted pair while both controls are still visible.

Accessibility

The error is a persistent text message linked through aria-describedby, both inputs expose aria-invalid, and updates are announced through role status. Native date inputs remain keyboard operable. Main text contrast is 15.19:1 light and 13.07:1 dark; error text is 8.2:1 light and 10.25:1 dark.

Was this useful? Send feedback.