49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import * as React from 'react';
|
||
|
|
|
||
|
|
import { cn } from '@/lib/utils';
|
||
|
|
|
||
|
|
export interface FieldErrorProps extends React.HTMLAttributes<HTMLParagraphElement> {
|
||
|
|
/**
|
||
|
|
* The error message to render. When falsy the component renders an
|
||
|
|
* empty live region so a screen reader still picks up subsequent
|
||
|
|
* error messages without an aria-live remount.
|
||
|
|
*/
|
||
|
|
message?: string | null | undefined;
|
||
|
|
/**
|
||
|
|
* Optional id — pair with `aria-describedby` on the associated input
|
||
|
|
* so SR users hear the error after the input's accessible name.
|
||
|
|
*/
|
||
|
|
id?: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Accessible error renderer for form fields. Always renders a
|
||
|
|
* `role="alert"` + `aria-live="polite"` region so SR users get
|
||
|
|
* immediate feedback when validation fires. Hide visually when
|
||
|
|
* `message` is empty without removing the region from the DOM —
|
||
|
|
* tearing the live region down between submits delays the next
|
||
|
|
* announcement on most assistive tech.
|
||
|
|
*
|
||
|
|
* Caller is responsible for setting `aria-invalid` and
|
||
|
|
* `aria-describedby={id}` on the linked input.
|
||
|
|
*/
|
||
|
|
export function FieldError({ message, id, className, ...props }: FieldErrorProps) {
|
||
|
|
return (
|
||
|
|
<p
|
||
|
|
id={id}
|
||
|
|
role="alert"
|
||
|
|
aria-live="polite"
|
||
|
|
className={cn(
|
||
|
|
'text-xs text-destructive',
|
||
|
|
!message && 'sr-only', // empty state keeps the region for next message
|
||
|
|
className,
|
||
|
|
)}
|
||
|
|
{...props}
|
||
|
|
>
|
||
|
|
{message ?? ''}
|
||
|
|
</p>
|
||
|
|
);
|
||
|
|
}
|