Blog>
Snippets

Implementing Accessible Error Handling in TanStack Form

Demonstrate how to display error messages in an accessible way using TanStack Form, ensuring that error messages are announced by screen readers.
import { useForm, ErrorMessage } from '@tanstack/react-form';

// Define your form
function MyForm() {
  const {
    Form,
    meta: { isSubmitting, isValidating, error },
  } = useForm({
    // Form configuration and validation schema
  });

  return (
    <Form>
      <div>
        // Accessible input field example
        <label htmlFor="email">Email</label>
        <input id="email" type="email" aria-describedby="email-error" />
        <ErrorMessage name="email" />
        // Error message that will be linked to the input via 'aria-describedby'
        <span id="email-error" role="alert">
          <ErrorMessage name="email" />
        </span>
      </div>
    </Form>
  );
}
This code demonstrates how to use TanStack Form to create an accessible form field with an error message. The 'ErrorMessage' component is used to display the error message for the 'email' field. By using 'aria-describedby' on the input and linking it with an 'id' on the span that contains the 'ErrorMessage', screen readers can announce the error message when the input is focused or when the error message changes. This ensures that users who rely on screen readers are aware of any errors in their input.