Forms · Complete runnable example

Form validation with inline errors

Make errors specific and easy to find, with a clear distinction between validation and delivery.

Live example

This preview runs in an isolated document. Clipboard writes and saved preferences may be blocked, and printing requires the standalone file. A dialog affects only the example. Reset reloads the original example state.

When to use it

Use this example to learn how a small form can explain missing or invalid values. It validates a name and email address locally and deliberately contains no submission service.

Try the important details

  1. Submit empty fields and check the inline messages and first-invalid-field focus.
  2. Enter an invalid email, correct it, and check that the error state updates.
  3. Enter valid values. The message says “Demo validated. Nothing was sent”.

How it works

  • Visible labels identify each field. Help and error text are associated using aria-describedby.
  • Validation changes aria-invalid and focuses the first invalid field after a failed attempt.
  • Error and status strings are assigned as text. No fetch request, email delivery, or account creation occurs.

The complete source

The preview, copied text, and downloaded file use this same document.

HTML

<!doctype html>
<!--
MIT License
Copyright (c) 2026 MRHTML

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:; connect-src 'none'; form-action 'none'; object-src 'none'; base-uri 'none'"
    />
    <title>Accessible local form validation | MRHTML</title>
    <style>
      /* MRHTML standalone example. No external styles, fonts, or assets. */
      :root {
        color-scheme: light;
        --paper: #f5f3ee;
        --surface: #fff;
        --ink: #1e2b42;
        --muted: #59657a;
        --line: #d9dee7;
        --soft: #eef1fb;
        --blue: #344ed5;
        --blue-hover: #263caf;
        --button-text: #fff;
        --focus: #b65716;
        --error: #ad253d;
        font:
          16px/1.6 system-ui,
          -apple-system,
          BlinkMacSystemFont,
          'Segoe UI',
          sans-serif;
        color: var(--ink);
        background: var(--paper);
      }
      * {
        box-sizing: border-box;
      }
      body {
        margin: 0;
        min-height: 100svh;
        display: grid;
        place-items: center;
        padding: 40px 24px;
      }
      main {
        width: min(680px, 100%);
        min-width: 0;
      }
      h1,
      h2,
      h3,
      p {
        margin: 0;
      }
      h1,
      h2,
      h3 {
        line-height: 1.15;
        letter-spacing: -0.045em;
      }
      h1 {
        font-size: clamp(1.9rem, 5vw, 2.65rem);
        font-weight: 650;
        max-width: 570px;
      }
      h2 {
        font-size: 1.35rem;
        font-weight: 650;
      }
      p {
        color: var(--muted);
      }
      button,
      input,
      textarea {
        font: inherit;
      }
      button {
        cursor: pointer;
      }
      button:disabled {
        cursor: not-allowed;
        opacity: 0.65;
      }
      button,
      a,
      input,
      textarea {
        -webkit-tap-highlight-color: transparent;
      }
      :focus-visible {
        outline: 3px solid var(--focus);
        outline-offset: 4px;
      }
      .eyebrow {
        display: flex;
        align-items: center;
        gap: 10px;
        color: var(--muted);
        font-size: 0.65rem;
        font-weight: 650;
        letter-spacing: 0.13em;
        text-transform: uppercase;
        margin-bottom: 22px;
      }
      .eyebrow::before {
        content: '';
        width: 8px;
        height: 8px;
        background: var(--blue);
        border-radius: 50%;
      }
      .intro {
        font-size: 0.94rem;
        max-width: 540px;
        margin-top: 17px;
      }
      .card {
        margin-top: 28px;
        padding: 28px;
        background: var(--surface);
        border: 1px solid var(--line);
        border-radius: 16px;
        box-shadow: 0 8px 28px #14264a05;
      }
      .card-label {
        color: var(--muted);
        font-size: 0.62rem;
        font-weight: 650;
        letter-spacing: 0.11em;
        text-transform: uppercase;
        margin-bottom: 11px;
      }
      .button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 13px;
        padding: 12px 19px;
        min-height: 46px;
        border: 1px solid transparent;
        border-radius: 8px;
        background: var(--blue);
        color: var(--button-text);
        font-size: 0.85rem;
        font-weight: 600;
        line-height: 1.45;
        transition:
          background 0.15s,
          transform 0.15s;
      }
      .button:hover:not(:disabled) {
        background: var(--blue-hover);
        transform: translateY(-1px);
      }
      .button.secondary {
        background: var(--surface);
        border-color: var(--line);
        color: var(--ink);
      }
      .button.secondary:hover:not(:disabled) {
        background: var(--soft);
      }
      .button svg {
        display: block;
        width: 18px;
        height: 18px;
        flex: none;
      }
      .hint {
        font-size: 0.74rem;
        line-height: 1.75;
        margin-top: 20px;
        max-width: 570px;
      }
      .status {
        min-height: 1.6em;
        margin-top: 17px;
        font-size: 0.8rem;
        color: var(--ink);
        overflow-wrap: anywhere;
      }
      .actions {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px;
      }
      [hidden] {
        display: none !important;
      }
      @media (max-width: 430px) {
        body {
          padding: 30px 18px;
        }
        .card {
          padding: 23px 20px;
        }
        .eyebrow {
          font-size: 0.6rem;
          letter-spacing: 0.11em;
        }
        .intro {
          font-size: 0.88rem;
        }
      }
      @media (prefers-reduced-motion: reduce) {
        *,
        *::before,
        *::after {
          animation: none !important;
          transition: none !important;
        }
        .button:hover:not(:disabled) {
          transform: none;
        }
      }

      .form-heading {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 18px;
        padding-bottom: 22px;
        border-bottom: 1px solid var(--line);
        margin-bottom: 25px;
      }
      .form-heading > span {
        background: var(--soft);
        color: #334a93;
        padding: 5px 9px;
        border-radius: 6px;
        font-size: 0.62rem;
        white-space: nowrap;
      }
      .form-heading p {
        font-size: 0.77rem;
        margin-top: 9px;
      }
      .fields {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 23px;
      }
      .field {
        min-width: 0;
      }
      .field label {
        display: block;
        font-size: 0.84rem;
        font-weight: 600;
        margin-bottom: 9px;
      }
      .field label span {
        font-size: 0.66rem;
        font-weight: 400;
        color: var(--muted);
      }
      .field input {
        width: 100%;
        min-height: 49px;
        border: 1px solid #adb9cd;
        border-radius: 7px;
        padding: 11px 13px;
        color: var(--ink);
        background: var(--surface);
        font-size: 16px;
      }
      .field input::placeholder {
        color: #6a7589;
        opacity: 1;
      }
      .field input[aria-invalid='true'] {
        border: 2px solid var(--error);
        padding: 10px 12px;
      }
      .field-hint {
        font-size: 0.65rem;
        margin-top: 8px;
      }
      .field-error {
        font-size: 0.73rem;
        color: var(--error);
        margin-top: 8px;
        font-weight: 550;
      }
      .form-actions {
        margin-top: 28px;
      }
      .form-status[data-kind='success'] {
        color: #22603a;
        padding: 13px 15px;
        background: #edf7ed;
        border: 1px solid #a9c9ac;
        border-radius: 7px;
      }
      .form-status[data-kind='error'] {
        color: var(--error);
      }
      @media (max-width: 600px) {
        .fields {
          grid-template-columns: 1fr;
          gap: 23px;
        }
        .form-heading {
          flex-wrap: wrap;
          gap: 12px;
        }
      }
    </style>
  </head>
  <body>
    <main>
      <p class="eyebrow">MRHTML / Form feedback</p>
      <h1>Useful feedback.<br />Right where it's needed.</h1>
      <p class="intro">
        A small form with associated error messages, clear focus, and honest
        local validation.
      </p>
      <form class="card" id="demo-form" novalidate>
        <div class="form-heading">
          <div>
            <h2>Try a sample introduction.</h2>
            <p>Use example details. This demo sends nothing.</p>
          </div>
          <span>LOCAL DEMO</span>
        </div>
        <div class="fields">
          <div class="field">
            <label for="demo-name">Your name <span>(required)</span></label
            ><input
              id="demo-name"
              name="name"
              autocomplete="name"
              required
              maxlength="80"
              placeholder="Sam from MRHTML"
              aria-describedby="name-hint name-error"
            />
            <p class="field-hint" id="name-hint">
              Any name you would like to use.
            </p>
            <p class="field-error" id="name-error" hidden></p>
          </div>
          <div class="field">
            <label for="demo-email">Email address <span>(required)</span></label
            ><input
              id="demo-email"
              name="email"
              type="email"
              autocomplete="email"
              required
              maxlength="254"
              placeholder="you@example.com"
              aria-describedby="email-hint email-error"
            />
            <p class="field-hint" id="email-hint">
              Format is checked, not mailbox ownership.
            </p>
            <p class="field-error" id="email-error" hidden></p>
          </div>
        </div>
        <div class="actions form-actions">
          <button class="button" id="validate-button" type="button" disabled>
            Validate the demo
            <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
              <path
                d="M4 10h12m-5-5 5 5-5 5"
                stroke="currentColor"
                stroke-width="1.6"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg></button
          ><button class="button secondary" type="reset">Reset</button>
        </div>
        <p class="status form-status" id="form-status" role="status"></p>
        <noscript
          ><p class="hint">
            JavaScript is off. Demo validation is unavailable and the submit
            button stays disabled. Nothing will be sent.
          </p></noscript
        >
      </form>
      <p class="hint">
        Try leaving a field empty. Validation happens in this page only; a real
        form also needs server-side validation and a verified submission
        destination.
      </p>
    </main>

    <script>
      // MRHTML local validation demo. No fetch, backend, email, or stored form data.
      const form = document.getElementById('demo-form');
      const nameField = document.getElementById('demo-name');
      const emailField = document.getElementById('demo-email');
      const status = document.getElementById('form-status');
      const fields = [nameField, emailField];
      let attempted = false;
      document.getElementById('validate-button').disabled = false;
      function errorFor(field) {
        if (field === nameField && !field.value.trim())
          return 'Enter a name before continuing.';
        if (field === emailField && field.validity.valueMissing)
          return 'Enter an email address before continuing.';
        if (field === emailField && field.validity.typeMismatch)
          return 'Use an email address in the format you@example.com.';
        if (field.validity.tooLong)
          return `Use no more than ${field.maxLength} characters.`;
        return '';
      }
      function validateField(field) {
        const error = document.getElementById(
          field === nameField ? 'name-error' : 'email-error',
        );
        const message = errorFor(field);
        // Assign plain text, never HTML assembled from user input.
        error.textContent = message;
        error.hidden = !message;
        if (message) field.setAttribute('aria-invalid', 'true');
        else field.removeAttribute('aria-invalid');
        return !message;
      }
      function validateDemo() {
        attempted = true;
        const invalidFields = fields.filter((field) => !validateField(field));
        if (invalidFields.length) {
          status.dataset.kind = 'error';
          status.textContent = `Please correct ${invalidFields.length === 1 ? 'the highlighted field' : 'the highlighted fields'}.`;
          invalidFields[0].focus();
          return;
        }
        status.dataset.kind = 'success';
        status.textContent = 'Demo validated. Nothing was sent';
      }
      // Explicit local actions also work in a sandbox without allow-forms.
      document
        .getElementById('validate-button')
        .addEventListener('click', (event) => {
          event.preventDefault();
          validateDemo();
        });
      form.addEventListener('keydown', (event) => {
        if (
          event.key === 'Enter' &&
          event.target instanceof HTMLInputElement &&
          !event.isComposing
        ) {
          event.preventDefault();
          validateDemo();
        }
      });
      // Keep a prevented submit fallback when adapting this as a standalone form.
      form.addEventListener('submit', (event) => {
        event.preventDefault();
        validateDemo();
      });
      fields.forEach((field) => {
        field.addEventListener('input', () => {
          status.textContent = '';
          delete status.dataset.kind;
          if (attempted) validateField(field);
        });
      });
      form.addEventListener('reset', () => {
        attempted = false;
        fields.forEach((field) => field.removeAttribute('aria-invalid'));
        ['name-error', 'email-error'].forEach((id) => {
          const error = document.getElementById(id);
          error.textContent = '';
          error.hidden = true;
        });
        delete status.dataset.kind;
        status.textContent = 'Form cleared.';
      });
    </script>
  </body>
</html>