Sub topic 1
Anatomy of a Well-Built Form Field
A form field is a small unit with a label, an input, optional help text, and an error message. Each part has a job, and a field works well only when all of them are present and linked. This chapter covers the structure of a field, how to group fields, how to track their state, and when to validate them.
Prerequisites
You should know basic HTML form elements (input, label, select, button), basic TypeScript, and how a browser submits form data. You should also be comfortable reading a simple state object.
Anatomy of a well-built form field
Link every input to a visible label with for and id. Connect hints and errors with aria-describedby so screen readers announce them with the input.
<div>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required
aria-describedby="email-hint email-error" aria-invalid="true">
<p id="email-hint">We only use this to send your receipt.</p>
<p id="email-error">Enter an email address in the format [email protected].</p>
</div>Grouping, ordering, and layout
- Place related fields together, such as name fields or shipping fields.
- Keep one logical order from top to bottom. Tab order should match the visual order.
- Wrap a set of related radio buttons or checkboxes in
<fieldset>with a<legend>. - Use one column on small screens so the reading order stays clear.
Tracking form state
Each field needs more than its value. Track whether the user has touched it (left it after focusing), whether the value is dirty (changed from its initial value), and any current error. Those flags decide when to show a message.
type FieldState = {
value: string;
touched: boolean;
dirty: boolean;
error?: string;
};
function onBlur(state: FieldState): FieldState {
return { ...state, touched: true };
}
function onChange(state: FieldState, value: string, initial: string): FieldState {
return { ...state, value, dirty: value !== initial };
}> Note: showing an error before the user has touched a field is distracting. Show errors only after touch or a failed submit.
Validation rules and when to run them
Choose the timing for each rule. Running every rule on every keystroke produces noise, and running them only on submit delays feedback.
| Timing | When it runs | Best for |
|---|---|---|
| On input | Each change | Format hints, character counts |
| On blur | When the user leaves the field | Email, required fields |
| On step change | When the user moves to the next step | Multi-step forms |
| On submit | When the user submits | Cross-field checks, final guard |
Exercise
A required email field has been touched but is empty. Should the error appear on blur or on submit, and why?
Show answer
On blur. The user has left the field, so the error is relevant and actionable now. Showing it on submit alone delays the fix, and showing it before any touch is distracting.