Forms
Labels, help, validation and submit, with Field, react-hook-form and zod.
Field lays out a label, control, help text and error. This pattern wires it to react-hook-form and zod so every field validates the same way. Submit with everything empty to see the errors.
Installation
npm install react-hook-form zod @hookform/resolversHow it works
- Each field is a
ControllerrenderingField. When it's invalid,data-invalidon theFieldandaria-invalidon the control turn on the error style, andFieldErrorshows the message from the schema. - The error replaces the help text, so the field doesn't grow two lines.
- Base UI's
Selecttakes its options asitems; the item withvalue: nullis the placeholder. Map an empty form value tonulland back. - On success, a Toast confirms it. Errors never go in a toast.
Guidelines
- Write error messages as what to do ("Enter a work email, like name@company.lk."), not what's wrong ("Invalid input").
- Validate on submit, then live on the fields that failed. Don't show errors while someone is still typing their first attempt.
- Primary action last and
brandif it's the view's main action; Cancel isoutline. While submitting, disable it and change the label ("Adding employee"). - One column. Group long forms with
FieldSetandFieldLegend, or split them into steps.