Skip to content

Form ​

Form validation with the browser's own rules: messages under each field, an error summary that takes focus, and live checks after the first attempt.

Installation ​

bash
npx bootcn add form
bash
pnpm dlx bootcn add form
bash
yarn dlx bootcn add form
bash
bunx --bun bootcn add form

The CLI also installs the design tokens and these components: field, label, input, select, checkbox, button. It prints the <link> and <script> tags to add to your layout.

Usage ​

Validate on the server as well. To show server errors, render the same markup: aria-invalid="true" on the field, the message in its .bootcn-field__error (without hidden), and the summary filled in and visible. Works with the Checkbox group component, whose minimum is a custom validity message.

JavaScript API ​

  • data-bootcn-form and novalidate on the <form>: the browser's constraint rules (required, type="email", minlength, pattern, min/max…) still apply, but Bootcn shows the messages.
  • Each field lists its error element (.bootcn-field__error) in aria-describedby; the field gets aria-invalid="true" and the message. Override a browser message with data-error-value-missing, data-error-type-mismatch, data-error-too-short, data-error-pattern-mismatch and the other data-error-* names of the ValidityState flags.
  • data-bootcn-form-summary (optional): an error summary listing every problem as a link to its field. It is shown and focused when a submission fails; without it, the first invalid field gets focus.
  • Fields are checked when left with a value, and on every change after the first submission.
  • Events (bubble): bootcn:form:invalid (detail.fields) and bootcn:form:submit (cancelable, detail.data is a FormData). A form without action is handled in JavaScript only and shows data-success (or "Saved.") in data-bootcn-form-success; with action it posts normally unless a listener calls preventDefault().
  • Bootcn.form.validate(form) returns true or false; init() / destroy().

Accessibility ​

  • Errors are text linked to their fields with aria-describedby, and fields are marked aria-invalid, so screen readers read the message with the label.
  • On a failed submission the error summary takes focus and is read with its heading ("There are 3 problems"); each link moves focus to its field.
  • Messages appear after a field is left or the form is submitted, not while someone is still typing.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.
  • The field component.
  • The label component.
  • The input component.
  • The select component.
  • The checkbox component.
  • The button component.

Source ​

The exact files the CLI installs (form@1.0.1). View on GitHub · Report an issue

html
<form class="bootcn-form" data-bootcn-form novalidate aria-labelledby="bootcn-form-title">
  <h2 class="bootcn-form__title" id="bootcn-form-title">Create an account</h2>
  <div
    class="bootcn-form__summary"
    tabindex="-1"
    aria-labelledby="bootcn-form-summary-title"
    data-bootcn-form-summary
    hidden
  >
    <h3 class="bootcn-form__summary-title" id="bootcn-form-summary-title">
      <svg
        class="bootcn-icon"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        focusable="false"
      >
        <circle cx="12" cy="12" r="9" />
        <path d="M12 8v4" />
        <path d="M12 16h.01" />
      </svg>
      <span data-bootcn-form-summary-count>Fix the following:</span>
    </h3>
    <ul class="bootcn-form__summary-list" data-bootcn-form-summary-list></ul>
  </div>
  <div class="bootcn-field">
    <label class="bootcn-label" for="bootcn-form-name">Full name</label>
    <input
      class="form-control bootcn-input"
      type="text"
      id="bootcn-form-name"
      name="name"
      autocomplete="name"
      aria-describedby="bootcn-form-name-error"
      required
      data-error-value-missing="Enter your full name."
    />
    <p class="bootcn-field__error" id="bootcn-form-name-error" hidden></p>
  </div>
  <div class="bootcn-field">
    <label class="bootcn-label" for="bootcn-form-email">Email</label>
    <input
      class="form-control bootcn-input"
      type="email"
      id="bootcn-form-email"
      name="email"
      autocomplete="email"
      aria-describedby="bootcn-form-email-error"
      required
      data-error-value-missing="Enter your email address."
      data-error-type-mismatch="Enter an email address like name@example.com."
    />
    <p class="bootcn-field__error" id="bootcn-form-email-error" hidden></p>
  </div>
  <div class="bootcn-field">
    <label class="bootcn-label" for="bootcn-form-password">Password</label>
    <input
      class="form-control bootcn-input"
      type="password"
      id="bootcn-form-password"
      name="password"
      autocomplete="new-password"
      aria-describedby="bootcn-form-password-error bootcn-form-password-help"
      required
      minlength="8"
      data-error-value-missing="Choose a password."
      data-error-too-short="Use at least 8 characters."
    />
    <p class="bootcn-field__error" id="bootcn-form-password-error" hidden></p>
    <p class="bootcn-field__help" id="bootcn-form-password-help">At least 8 characters.</p>
  </div>
  <div class="bootcn-field">
    <label class="bootcn-label" for="bootcn-form-plan">Plan</label>
    <select
      class="form-select bootcn-select"
      id="bootcn-form-plan"
      name="plan"
      required
      aria-describedby="bootcn-form-plan-error"
      data-error-value-missing="Choose a plan."
    >
      <option value="">Choose a plan</option>
      <option value="hobby">Hobby</option>
      <option value="pro">Pro</option>
      <option value="team">Team</option>
    </select>
    <p class="bootcn-field__error" id="bootcn-form-plan-error" hidden></p>
  </div>
  <div class="bootcn-field">
    <div class="form-check bootcn-checkbox">
      <input
        class="form-check-input bootcn-checkbox__input"
        type="checkbox"
        id="bootcn-form-terms"
        name="terms"
        value="1"
        required
        aria-describedby="bootcn-form-terms-error"
        data-error-value-missing="Accept the terms to continue."
      />
      <label class="form-check-label bootcn-checkbox__label" for="bootcn-form-terms">
        I accept the terms and conditions
      </label>
    </div>
    <p class="bootcn-field__error" id="bootcn-form-terms-error" hidden></p>
  </div>
  <button type="submit" class="btn bootcn-button bootcn-button--default">Create account</button>
  <p class="bootcn-form__success" role="status" data-bootcn-form-success></p>
</form>
css
.bootcn-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 24rem;
  max-width: 100%;
}

.bootcn-form .bootcn-field {
  margin: 0;
}

.bootcn-form__title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}

.bootcn-form__summary {
  padding: 0.875rem 1rem;
  border: var(--bootcn-border-width) solid var(--bs-danger);
  border-radius: var(--bootcn-radius-lg);
  background-color: var(--bootcn-destructive-subtle);
  color: var(--bootcn-destructive-text);
  outline: 0;
}

.bootcn-form__summary:focus-visible {
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-form__summary[hidden] {
  display: none;
}

.bootcn-form__summary-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0 0 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
}

.bootcn-form__summary-list {
  margin: 0;
  padding-inline-start: 1.5rem;
  font-size: 0.875rem;
}

.bootcn-form__summary-list a {
  color: inherit;
  text-underline-offset: 0.2em;
}

.bootcn-form .bootcn-field__error[hidden] {
  display: none;
}

.bootcn-form [aria-invalid='true'].form-select,
.bootcn-form [aria-invalid='true'].form-check-input {
  border-color: var(--bs-danger);
}

.bootcn-form__success {
  margin: 0;
  color: var(--bootcn-success-text);
  font-size: 0.875rem;
}

.bootcn-form__success:empty {
  display: none;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.form) return; // already loaded: idempotent

  const ROOT = '[data-bootcn-form]';
  // ValidityState flags, in the order they are reported, and the
  // data-error-* attribute that overrides each message.
  const FLAGS = [
    ['valueMissing', 'data-error-value-missing'],
    ['typeMismatch', 'data-error-type-mismatch'],
    ['patternMismatch', 'data-error-pattern-mismatch'],
    ['tooShort', 'data-error-too-short'],
    ['tooLong', 'data-error-too-long'],
    ['rangeUnderflow', 'data-error-range-underflow'],
    ['rangeOverflow', 'data-error-range-overflow'],
    ['stepMismatch', 'data-error-step-mismatch'],
    ['badInput', 'data-error-bad-input'],
  ];
  let listening = false;

  function fields(form) {
    return Array.from(form.elements).filter(function (el) {
      return el.willValidate && el.type !== 'submit' && el.type !== 'button';
    });
  }

  function messageFor(field) {
    const v = field.validity;
    for (let i = 0; i < FLAGS.length; i += 1) {
      if (v[FLAGS[i][0]]) return field.getAttribute(FLAGS[i][1]) || field.validationMessage;
    }
    return field.validationMessage;
  }

  function errorElement(field) {
    const ids = (field.getAttribute('aria-describedby') || '').split(/\s+/);
    for (let i = 0; i < ids.length; i += 1) {
      const el = ids[i] && document.getElementById(ids[i]);
      if (el && el.classList.contains('bootcn-field__error')) return el;
    }
    return null;
  }

  function show(field) {
    const valid = field.checkValidity();
    const error = errorElement(field);
    if (valid) field.removeAttribute('aria-invalid');
    else field.setAttribute('aria-invalid', 'true');
    if (error) {
      error.textContent = valid ? '' : messageFor(field);
      error.hidden = valid;
    }
    return valid;
  }

  function labelText(field) {
    const label = field.labels && field.labels[0];
    if (label) return label.textContent.trim().replace(/\s+/g, ' ');
    const group = field.closest('fieldset');
    const legend = group && group.querySelector('legend');
    return legend ? legend.textContent.trim() : field.name;
  }

  function summarize(form, invalid) {
    const summary = form.querySelector('[data-bootcn-form-summary]');
    if (!summary) return null;
    const list = summary.querySelector('[data-bootcn-form-summary-list]');
    const count = summary.querySelector('[data-bootcn-form-summary-count]');
    if (list) {
      list.replaceChildren();
      invalid.forEach(function (field) {
        const item = document.createElement('li');
        const link = document.createElement('a');
        link.href = '#' + field.id;
        link.textContent = labelText(field) + ': ' + messageFor(field);
        item.appendChild(link);
        list.appendChild(item);
      });
    }
    if (count) {
      count.textContent =
        invalid.length === 1 ? 'There is 1 problem' : 'There are ' + invalid.length + ' problems';
    }
    summary.hidden = invalid.length === 0;
    return summary;
  }

  // Validates every field; returns the invalid ones (radio groups once).
  function validate(form) {
    const seen = new Set();
    const invalid = [];
    fields(form).forEach(function (field) {
      if (field.type === 'radio') {
        if (seen.has(field.name)) return;
        seen.add(field.name);
      }
      if (!show(field)) invalid.push(field);
    });
    return invalid;
  }

  function onSubmit(event) {
    const form = event.target;
    if (!form.matches || !form.matches(ROOT)) return;
    form.dataset.bootcnSubmitted = 'true';
    const invalid = validate(form);
    const success = form.querySelector('[data-bootcn-form-success]');
    if (success) success.textContent = '';
    if (invalid.length) {
      event.preventDefault();
      const summary = summarize(form, invalid);
      if (summary) summary.focus();
      else invalid[0].focus();
      form.dispatchEvent(
        new CustomEvent('bootcn:form:invalid', { bubbles: true, detail: { fields: invalid } }),
      );
      return;
    }
    summarize(form, []);
    const custom = new CustomEvent('bootcn:form:submit', {
      bubbles: true,
      cancelable: true,
      detail: { data: new FormData(form) },
    });
    const handled = !form.dispatchEvent(custom);
    if (handled || !form.hasAttribute('action')) {
      event.preventDefault();
      if (success && !handled) success.textContent = form.getAttribute('data-success') || 'Saved.';
    }
  }

  // Before the first submit, a field is checked when it is left with a
  // value; after it, every change is checked right away.
  function onInput(event) {
    const field = event.target;
    const form = field.form;
    if (!form || !form.matches(ROOT) || !field.willValidate) return;
    if (form.dataset.bootcnSubmitted === 'true' || field.getAttribute('aria-invalid') === 'true') {
      show(field);
      const summary = form.querySelector('[data-bootcn-form-summary]');
      if (summary && !summary.hidden) {
        const invalid = fields(form).filter(function (other) {
          return other.getAttribute('aria-invalid') === 'true';
        });
        summarize(form, invalid);
      }
    }
  }

  function onFocusOut(event) {
    const field = event.target;
    const form = field.form;
    if (!form || !form.matches || !form.matches(ROOT) || !field.willValidate) return;
    if (field.value !== '' && field.type !== 'checkbox' && field.type !== 'radio') show(field);
  }

  function onClick(event) {
    const link = event.target.closest && event.target.closest('[data-bootcn-form-summary-list] a');
    if (!link) return;
    const field = document.getElementById(link.getAttribute('href').slice(1));
    if (!field) return;
    event.preventDefault();
    field.focus();
    field.scrollIntoView({ block: 'center' });
  }

  function init() {
    if (listening) return;
    document.addEventListener('submit', onSubmit);
    document.addEventListener('input', onInput);
    document.addEventListener('change', onInput);
    document.addEventListener('focusout', onFocusOut);
    document.addEventListener('click', onClick);
    listening = true;
  }

  function destroy() {
    if (!listening) return;
    document.removeEventListener('submit', onSubmit);
    document.removeEventListener('input', onInput);
    document.removeEventListener('change', onInput);
    document.removeEventListener('focusout', onFocusOut);
    document.removeEventListener('click', onClick);
    listening = false;
  }

  ns.form = {
    init: init,
    destroy: destroy,
    validate: function (form) {
      const invalid = validate(form);
      summarize(form, invalid);
      return invalid.length === 0;
    },
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.