aria-errormessage allows to associate the error message with an input or form element, allowing assistive technologies to announce the error when element is invalid.

When to use

  • To provide accessible error messages for form inputs.
  • When you need to dynamically display error messages based on user input.
  • When you want to explicitly link the error message to a specific input.

Use aria-errormessage together with aria-invalid on an input to indicate that the field is invalid.

import { useState } from "react";  
  
function EmailInput({ error }) {  
  return (  
    <div>  
      <label htmlFor="email">Email Address</label>  
      <input  
        id="email"  
        type="email"  
        aria-invalid={error ? "true" : "false"}  
        aria-errormessage={error ? "email-error" : undefined}  
      />  
      {error && (  
        <div id="email-error" aria-live="polite" role="alert">  
          {error}  
        </div>  
      )}  
    </div>  
  );  
}  
  
// Usage  
function App() {  
  const [email, setEmail] = useState("");  
  const [error, setError] = useState(null);  
  
  const validateEmail = (value) => {  
    if (!value.includes("@")) {  
      setError("Please enter a valid email address.");  
    } else {  
      setError(null);  
    }  
  };  
  
  return (  
    <EmailInput  
      error={error}  
      onBlur={(e) => validateEmail(e.target.value)}  
    />  
  );  
}