Terndesk, the keyboard-first email client with a CLI. Holiday offer: $29 instead of $49. Get it →

Form Error Messages: 10 Examples and aria-describedby

Form Error Messages: 10 Examples and aria-describedby

17 min read
Static Forms Team
accessibilityformsuxjavascript
Share:

A good form error message names the field, says what is wrong, and says how to fix it, in words the person can act on without guessing. Compare "Invalid input" with "Enter an email address in the format name@example.com": the second one tells you the field, the problem and a valid value in a single line.

Most forms get one of two things wrong. The copy is vague, or the copy is fine but it only exists visually: a red border, or a line of text that a screen reader never connects to the field. This guide fixes both. You'll get 10 before-and-after rewrites, the aria-describedby and aria-invalid pattern that ties an error to its input, a short answer to the "aria-describedby vs placeholder" question, and a complete form that handles browser and server errors without wiping what the visitor typed.

We make Static Forms, a form backend, so the server section uses its real error responses as the example. Everything before that works with any backend. W3C and MDN sources were checked on 21 November 2026.

What makes a form error message useful

A useful error message answers three questions in one sentence:

  1. Which field? Use the field's label wording, so the message maps back to what the person sees.
  2. What's wrong? Describe the problem in their terms, not the validator's. "Too short", not "minlength constraint failed".
  3. How do I fix it? State the rule or give an example of a valid value.

Most of the time that fits in an instruction that starts with a verb: "Enter", "Choose", "Select", "Use". Instructions read as help. Verdicts like "Invalid" or "Wrong" read as blame and still leave the person to work out the fix.

WCAG 2.2 sets the floor here. Success criterion 3.3.1 Error Identification (level A) requires that when an input error is detected automatically, the item in error is identified and the error is described to the user in text. Success criterion 3.3.3 Error Suggestion (level AA) adds that when a correction is known, you suggest it, unless that would compromise security or the purpose of the content. A red border alone fails 3.3.1. "Invalid email" passes 3.3.1 and fails the spirit of 3.3.3, because you know what a valid email looks like and didn't say.

10 form error message examples, before and after

# Before After What changed
1 Invalid input Enter an email address in the format name@example.com Names the field and shows a valid value
2 This field is required Enter your company name Uses the label's wording, so the message stands alone in an error summary
3 Error: phone Enter a phone number using only digits, spaces and a leading + States the rule the validator applies
4 Password invalid Password must be 12 characters or more Says the actual requirement (show it before they type, too)
5 Passwords do not match Enter the same password in both fields Tells them what to do, not what failed
6 Invalid date Enter a start date that is today or later Explains the range instead of implying a format problem
7 File rejected Choose a PDF, JPG or PNG file smaller than 4 MB Lists allowed types and the size limit in one line
8 Message too short Message must be 10 characters or more Gives the number the validator uses
9 You must accept the terms Select the checkbox to agree to the privacy policy Names the control and the action, without the scolding tone
10 Oops! Something went wrong Your message wasn't sent because the connection failed. Try again. What you typed is still in the form. Says whether it was sent, why, and that nothing was lost

A few rules fall out of that table:

  • Don't make the person decode the validator. If the check is a pattern, describe the pattern in plain words. Never show a regular expression or an HTTP status code.
  • Keep the same text everywhere. The inline message and the matching line in the error summary should be identical, so people recognise it when they jump to the field.
  • Put requirements up front. If a password needs 12 characters, say so in a hint under the label. The error message then repeats a rule they've already seen.
  • Only show errors the visitor can fix. A failed webhook or a full quota on your side is not their problem to solve. Tell them whether the message was sent and what to do next, and log the technical detail for yourself.

Where and when to show the error

Inline errors, directly under or above the field, work best for field-level problems because the message sits next to the thing it's about. On a long form, add an error summary at the top after a failed submit. Keep a page-level banner for problems that aren't about any one field, such as a network failure.

Situation When to validate Where the message goes
Required text field After the field loses focus with content, and on submit Inline
Email or URL format After the field loses focus, then live while they correct it Inline
Password confirmation Once both fields have content Inline, on the second field
Several errors after submit On submit Summary at the top, plus each inline message
Network failure or server error After the request returns Status message near the submit button

Avoid validating on every keystroke from the first character. Someone who has typed "a" into an email field doesn't need to hear that it isn't an email yet. A pattern that works: validate when the field loses focus, and once a field is marked invalid, re-check it on every input so the error clears the moment it's fixed.

The accessible pattern: aria-describedby and aria-invalid

For each field that can fail, you need four things:

  1. A real <label> connected to the input with for and id.
  2. Visible error text near the field, in an element with its own id.
  3. aria-describedby on the input, pointing at that error element's id.
  4. aria-invalid="true" on the input while it's in error, removed once it's fixed.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Inline error pattern</title>
  <style>
    .error { color: #a10e22; margin: 0.25rem 0 0; }
    .error:empty { display: none; }
    [aria-invalid="true"] { border: 2px solid #a10e22; }
  </style>
</head>
<body>
  <label for="email">Email address</label>
  <p id="email-hint">We only use this to reply to you.</p>
  <input id="email" name="email" type="email" autocomplete="email"
    aria-describedby="email-error email-hint" aria-invalid="true">
  <p id="email-error" class="error">Enter an email address in the format name@example.com</p>
</body>
</html>

aria-describedby takes a space-separated list of ids, so one input can point at both its error and its hint. Put the error id first, so the fix is read before the general hint. The error element can stay in the list when it's empty: an empty element adds nothing to the description, which means your script only has to change the text and the aria-invalid value.

With this wiring, a screen reader user who lands on the field hears the label, that the field is invalid, and the description, which now starts with the error. The exact order and wording vary between screen readers, so listen to it once yourself. Without aria-describedby, the error is just a paragraph that happens to sit nearby, and someone tabbing through the form may never hear it.

Before and after diagram: with a placeholder as the only label, the hint disappears when typing and nothing tells the user what failed; with label for, aria-invalid and aria-describedby pointing at the error element, a screen reader reads the label, that the field is invalid, then the fix

aria-describedby vs placeholder

They do different jobs. A placeholder is a hint about what a value should look like; MDN says it is not a label and your form should never depend on it, and it disappears once someone types. aria-describedby links persistent, visible text, such as a hint or an error, to the input as its accessible description.

Use the placeholder for an optional example at most. Anything the person needs to finish the form belongs in visible text tied to the input with aria-describedby.

What about aria-errormessage?

ARIA also has aria-errormessage. It points at the element holding the error, is meant only for a field whose value is invalid, and goes together with aria-invalid="true". MDN adds that the element it references must be visible. This guide sticks with aria-describedby, the attribute the W3C forms tutorial uses for its inline errors, and it also carries the hint. If you add aria-errormessage, test it with the screen readers your visitors use.

When to set aria-invalid

MDN's advice on aria-invalid is to set it from your validation code, and not to set it on an empty required field until the person tries to submit, because they may still be filling the form in. The complete example below follows that: it validates a field on blur only if the person typed something, and checks every field on submit.

Move focus after a failed submit

When a submit fails, don't leave focus on the button. Either move focus to an error summary at the top of the form, with each line linking to its field, or move it to the first invalid field. The summary works better on long forms because it tells people how many problems there are before they start fixing them.

Browser validation: keep it, but replace its messages

Native constraint validation (required, type="email", minlength, pattern) already knows when a field is wrong. What it doesn't give you is control over the wording or placement: each browser shows its own bubble, with its own text, and it disappears after a few seconds.

The usual approach is to keep the attributes, add novalidate to the form so the browser doesn't show its bubbles, and read input.validity yourself to pick your message. That way the browser still does the checking and you still decide the words. The checkValidity vs reportValidity guide covers the APIs in detail, and form validation without JavaScript shows how far the attributes get you on their own.

One gap to know about: required treats a value of only spaces as filled in. If that matters, trim the value in your check, as the complete example below does.

Server errors: show what the visitor can act on

Browser validation is for speed. The server makes the final decision, because anything can post to an endpoint without running your page.

If your own backend returns errors per field, map them onto the same inline elements your client-side checks use. A common shape is an object keyed by field name, { "errors": { "email": "..." } }; loop over it, set each message with the same function, and focus the first one.

A hosted form backend usually doesn't validate your fields for you. Static Forms is an example: its API reference shows that errors come back as a single string with a status code, not a map of fields.

JSON
{
  "success": false,
  "error": "CAPTCHA verification failed. Please try again.",
  "code": "captcha_failed"
}

The documented cases include a missing or invalid API key (400 or 401), a domain that isn't on the form's allowed list or a failed CAPTCHA (403), and a submission limit or rate limit (429). Apart from the CAPTCHA, none of these are things the visitor can fix, and the raw text talks about API keys and plans. So:

  • Show the visitor whether the message was sent and what to do next, in your own words.
  • Log the error string to the console or your monitoring so you can fix the cause.
  • Treat a CAPTCHA failure as the one case to show near the challenge, with "Try the check again".
  • Keep everything they typed. Never reset the form on a failed request.

Two edge cases from the docs: a request over the 4.5 MB total limit is refused by the hosting platform with a 413 before Static Forms sees it, and that response has no CORS headers, so a cross-origin fetch fails as a network error rather than returning JSON. If your form takes files, check the total size in the browser first. The file input accept validation guide shows how.

Complete Working Example

This contact form validates in the browser with custom messages, links each error to its input with aria-describedby, shows an error summary on submit, sends the data to Static Forms as JSON, and turns server or network failures into a plain status message without clearing the form. Replace YOUR_API_KEY with the key from your Static Forms dashboard.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Contact us</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 560px; margin: 2rem auto; padding: 0 1rem; color: #172033; }
    .field { margin-top: 1.25rem; }
    label { display: block; font-weight: 600; }
    .hint { color: #4b5563; font-size: 0.9rem; margin: 0.25rem 0; }
    input, textarea { width: 100%; box-sizing: border-box; padding: 0.6rem; font: inherit; border: 1px solid #6b7280; border-radius: 4px; }
    [aria-invalid="true"] { border: 2px solid #a10e22; }
    .error { color: #a10e22; font-weight: 600; margin: 0.25rem 0 0; }
    .error:empty { display: none; }
    .summary { border: 3px solid #a10e22; padding: 1rem; margin-bottom: 1rem; }
    .summary h2 { margin-top: 0; font-size: 1.1rem; }
    .summary a { color: #a10e22; }
    :focus-visible { outline: 3px solid #2458d3; outline-offset: 3px; }
    button { margin-top: 1.5rem; padding: 0.7rem 1.4rem; font: inherit; }
  </style>
</head>
<body>
  <main>
    <h1>Contact us</h1>

    <div id="error-summary" class="summary" tabindex="-1" hidden>
      <h2>There is a problem</h2>
      <ul id="error-list"></ul>
    </div>

    <form id="contact-form" novalidate>
      <div class="field">
        <label for="name">Name</label>
        <input id="name" name="name" type="text" autocomplete="name" required
          aria-describedby="name-error">
        <p id="name-error" class="error"></p>
      </div>

      <div class="field">
        <label for="email">Email address</label>
        <p id="email-hint" class="hint">We only use this to reply to you.</p>
        <input id="email" name="email" type="email" autocomplete="email" required
          aria-describedby="email-error email-hint">
        <p id="email-error" class="error"></p>
      </div>

      <div class="field">
        <label for="message">Message</label>
        <p id="message-hint" class="hint">10 characters or more.</p>
        <textarea id="message" name="message" rows="5" required minlength="10"
          aria-describedby="message-error message-hint"></textarea>
        <p id="message-error" class="error"></p>
      </div>

      <button type="submit">Send message</button>
      <p id="form-status" role="status"></p>
    </form>
  </main>

  <script>
    const API_KEY = 'YOUR_API_KEY';
    const form = document.getElementById('contact-form');
    const summary = document.getElementById('error-summary');
    const errorList = document.getElementById('error-list');
    const status = document.getElementById('form-status');
    const button = form.querySelector('button[type="submit"]');
    const fields = ['name', 'email', 'message'].map((name) => form.elements[name]);

    // One message per validity state, worded as an instruction
    const messages = {
      name: { valueMissing: 'Enter your name' },
      email: {
        valueMissing: 'Enter your email address',
        typeMismatch: 'Enter an email address in the format name@example.com'
      },
      message: {
        valueMissing: 'Enter your message',
        tooShort: 'Message must be 10 characters or more'
      }
    };

    function messageFor(field) {
      const rules = messages[field.name];
      // required accepts a value of only spaces, so trim before checking
      if (field.required && field.value.trim() === '') return rules.valueMissing;
      for (const state of Object.keys(rules)) {
        if (field.validity[state]) return rules[state];
      }
      return '';
    }

    function setFieldError(field, text) {
      document.getElementById(field.id + '-error').textContent = text;
      if (text) field.setAttribute('aria-invalid', 'true');
      else field.removeAttribute('aria-invalid');
    }

    function showSummary(problems) {
      errorList.replaceChildren(...problems.map(({ field, text }) => {
        const item = document.createElement('li');
        const link = document.createElement('a');
        link.href = '#' + field.id;
        link.textContent = text;
        link.addEventListener('click', (event) => {
          event.preventDefault();
          field.focus();
        });
        item.append(link);
        return item;
      }));
      summary.hidden = problems.length === 0;
      if (problems.length > 0) summary.focus();
    }

    // Visitors see these instead of the API's error text, which is written for the site owner
    function visitorMessage(httpStatus, data) {
      if (data.code === 'captcha_failed') {
        return 'The spam check did not pass. Complete it again and resend. What you typed is still in the form.';
      }
      if (httpStatus >= 500) {
        return 'Your message was not sent because of a problem on our side. Try again in a few minutes. What you typed is still in the form.';
      }
      return 'Your message was not sent. Please email us directly instead. What you typed is still in the form.';
    }

    for (const field of fields) {
      // Validate when the visitor leaves a field they typed in
      field.addEventListener('blur', () => {
        if (field.value.trim() !== '') setFieldError(field, messageFor(field));
      });
      // Once a field is in error, clear the message as soon as it's fixed
      field.addEventListener('input', () => {
        if (field.getAttribute('aria-invalid') === 'true') setFieldError(field, messageFor(field));
      });
    }

    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      status.textContent = '';

      const problems = [];
      for (const field of fields) {
        const text = messageFor(field);
        setFieldError(field, text);
        if (text) problems.push({ field, text });
      }
      showSummary(problems);
      if (problems.length > 0) return;

      button.disabled = true;
      status.textContent = 'Sending your message…';

      try {
        const response = await fetch('https://api.staticforms.dev/submit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
          body: JSON.stringify({ apiKey: API_KEY, ...Object.fromEntries(new FormData(form)) })
        });
        const data = await response.json().catch(() => ({}));

        if (response.ok && data.success) {
          form.reset();
          status.textContent = 'Thanks, your message was sent. We will reply by email.';
        } else {
          console.error('Form submission failed:', response.status, data.error);
          status.textContent = visitorMessage(response.status, data);
        }
      } catch (error) {
        console.error('Form submission failed:', error);
        status.textContent = 'Your message was not sent because the connection failed. Check your connection and try again. What you typed is still in the form.';
      } finally {
        button.disabled = false;
      }
    });
  </script>
</body>
</html>

What it does, in order:

  • novalidate turns off the browser's bubbles, but required, type="email" and minlength still drive field.validity, and messageFor turns each state into an instruction.
  • Each input lists its error element first in aria-describedby. The script only changes the error text and aria-invalid, so the wiring never goes stale.
  • On submit, every field is checked, the summary lists each problem as a link to its field, and focus moves to the summary.
  • The status paragraph has role="status", so "Sending", success and failure are announced without moving focus.
  • A failed request logs the API's error for you and shows the visitor a message they can act on. The form keeps its values; only a successful send resets it.

Test it before you rely on it. Submit it empty, then with name@ as the email, then with a short message, and check the summary, the inline errors and the focus. Then post it with a wrong API key and confirm you see the visitor message and the logged error. Finally, go through the form once with a screen reader (VoiceOver on macOS, NVDA on Windows) and listen for the label, the invalid state and the error on each field.

Troubleshooting

What you see Why, and what to do
The screen reader reads the label but not the error aria-describedby is missing or points at an id that doesn't exist. Check the id spelling on both elements.
The error is announced even after it's fixed aria-invalid was never removed, or the error text wasn't cleared. Clear both in the same function.
The browser's own bubble appears on top of your message The form is missing novalidate, or you call reportValidity().
A field with only spaces passes as filled in required doesn't trim. Trim the value in your own check.
Errors appear while someone is still typing their first character You validate on input from the start. Validate on blur, then on input only once the field is invalid.
The form clears after a failed send form.reset() runs on every response. Reset only when the response says the submission succeeded.
fetch throws a network error for a large upload The request is over 4.5 MB in total and the hosting platform's 413 has no CORS headers. Check the size before sending.

FAQ

What should a form error message say?

It should name the field, say what is wrong, and say how to fix it, usually as one instruction such as "Enter an email address in the format name@example.com". Avoid generic text like "Invalid input" and anything that sounds like blame.

What is the difference between aria-describedby and placeholder?

A placeholder is a short example inside the input that disappears once someone types, and it is not a label. aria-describedby links visible text, such as a hint or an error message, to the input as its accessible description, so assistive technology announces it with the field. Use aria-describedby for anything the person needs.

Should I use aria-invalid on every field?

Set aria-invalid="true" only on a field that has failed validation, and remove it when the value is fixed. Don't set it on an empty field that nobody has touched yet, because the field isn't wrong until the visitor has had a chance to fill it in.

Is inline validation better than validating on submit?

Use both. Validate each field when the visitor leaves it so they can fix problems in context, and validate everything again on submit, with an error summary when there is more than one problem. The server still checks everything, because a request can skip your page.

Next steps

For the wider picture of accessible forms, read the form accessibility guide and the form UX best practices. For more client-side checks, see JavaScript form validation. When the form is ready, create a free form in the Static Forms dashboard, paste its key into the complete example, and the API reference lists every response your error handling might meet.