Agent Wranglers

APP-16Recommended

Check fields when people leave them

Check a field first when focus leaves it, then on every change once it shows an error, and check all fields on submit. Never show an error on a field nobody has touched.

How to do it

Track whether each field has been left once. Before that, stay silent while people type. After an error appears, check on every input, so the message goes away as soon as the value is fixed. On submit, check every field, then follow form errors for the messages and focus. Labels follow form labels. To style the field, use the CSS selectors :user-invalid and :user-valid. They match only after people interact with the field, while :invalid matches from page load.

Examples

TypeScript example

export function watchField(input: HTMLInputElement, validate: (value: string) => string | null, showError: (message: string | null) => void) {
  let isTouched = false;
  const run = () => showError(validate(input.value));
  input.addEventListener('blur', () => { isTouched = true; run(); });
  input.addEventListener('input', () => { if (isTouched && input.getAttribute('aria-invalid') === 'true') run(); });
}

Python example

from playwright.sync_api import expect

def test_email_error_waits_for_blur(page):
    page.goto("https://staging.example.com/signup")
    email = page.get_by_label("Email")
    email.fill("a")
    expect(email).not_to_have_attribute("aria-invalid", "true")
    email.blur()
    expect(email).to_have_attribute("aria-invalid", "true")
    email.fill("ada@example.com")
    expect(email).not_to_have_attribute("aria-invalid", "true")

How to check

A browser test types one letter into the email field. No error shows. It tabs away, and the error shows. It fixes the value, and the error goes away before focus leaves.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/app-ui/forms/validation-timing">Agent Wranglers web app interface playbook</a>. In code you write, add a comment next to it with the same link.