Forms and validation
Field, Form and react-hook-form, Zod, error summaries and submit states.
How far this is checked
Monoline does not depend on a form library, so react-hook-form is not installed in this repository. The snippets follow the react-hook-form v7 API and the Monoline prop names in this repo. The Monoline side of the register, Controller, summary and plain-state snippets (component names, props, ref targets, value types) was type-checked against @monoline/react with the react-hook-form calls stubbed. The library side (register options, Controller, resolvers) is written from the library docs and has not been run here. The Zod and TanStack Form snippets were not type-checked at all. Check versions against the library docs before you copy.
The pieces
Field- Label, hint and error around one control.
errormarks the control invalid, setsaria-describedbyand announces the message. Input, Textarea, NativeSelect, NumberInput, Combobox, SelectTrigger, DatePicker and Checkbox pick this up on their own. Form- A
<form>. Passerrors(an array of{name, message}) for a summary at the top; each item links to the control with thatnameand moves focus there.preventDefaultstops the native post for forms handled in JS. FormActions- The footer row. One
variant="solid"button per form. Button- Defaults to
type="button", so the submit button needstype="submit".loadingshows a spinner, setsaria-busyand ignores clicks, so a double click cannot submit twice.
Add noValidate to the form so your messages replace the browser's bubbles. Field required still sets the required attribute on the control, which is what assistive technology reads.
Native-like inputs: register
Input, Textarea, NativeSelect, PasswordInput and NumberInput forward ref to the real <input> and fire normal change and blur events, so {...register(name)} works as it does on a plain element. NumberInput returns a string unless you pass valueAsNumber: true; its step buttons dispatch an input event, so they update the form too.
import {useForm} from 'react-hook-form';
import {Button, Field, Form, FormActions, Input, NativeSelect, NumberInput, PasswordInput, Textarea} from '@monoline/react';
interface Values { email: string; password: string; plan: string; seats: number; notes: string }
export function SignupForm() {
const {register, handleSubmit, formState: {errors, isSubmitting}} = useForm<Values>({
defaultValues: {email: '', password: '', plan: 'team', seats: 5, notes: ''},
});
const onSubmit = async (values: Values) => { await saveAccount(values); };
return (
<Form noValidate onSubmit={handleSubmit(onSubmit)}>
<Field label="Email" required error={errors.email?.message}>
<Input type="email" autoComplete="email" {...register('email', {
required: 'Enter your email',
pattern: {value: /^\S+@\S+\.\S+$/, message: 'Enter an email like [email protected]'},
})} />
</Field>
<Field label="Password" hint="At least 12 characters." required error={errors.password?.message}>
<PasswordInput autoComplete="new-password" {...register('password', {
required: 'Choose a password',
minLength: {value: 12, message: 'Use at least 12 characters'},
})} />
</Field>
<Field label="Plan">
<NativeSelect {...register('plan')}>
<option value="solo">Solo</option>
<option value="team">Team</option>
</NativeSelect>
</Field>
<Field label="Seats" error={errors.seats?.message}>
<NumberInput min={1} max={500} {...register('seats', {valueAsNumber: true, min: {value: 1, message: 'At least one seat'}})} />
</Field>
<Field label="Notes">
<Textarea rows={3} {...register('notes')} />
</Field>
<FormActions>
<Button type="submit" variant="solid" loading={isSubmitting}>Create account</Button>
</FormActions>
</Form>
);
}
Value components: Controller
Combobox, Select, DatePicker, Checkbox and the rest do not expose a native change event, so connect them with Controller. The pattern is the same each time: value (or checked) from field.value, the change callback to field.onChange, ref to field.ref so react-hook-form can focus the first invalid control, and error on the Field from fieldState.error?.message.
Combobox:valueandonValueChange(value: string). It sends an empty string when the text is cleared.Select(Radix):valueandonValueChange(value: string)on the root, andrefandonBluronSelectTrigger. Start with''to show the placeholder.DatePicker:value: Date | nullandonValueChange(date: Date).refreaches the trigger button.Checkbox:checkedandonCheckedChange. The value can be'indeterminate', so convert withc === truefor a boolean field.
import {Controller, useForm} from 'react-hook-form';
import {
Button, Checkbox, Combobox, DatePicker, Field, Form, FormActions,
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@monoline/react';
interface Values { country: string; role: string; start: Date | null; terms: boolean }
const countries = [{value: 'in', label: 'India'}, {value: 'de', label: 'Germany'}, {value: 'us', label: 'United States'}];
export function ProfileForm() {
const {control, handleSubmit, formState: {isSubmitting}} = useForm<Values>({
defaultValues: {country: '', role: '', start: null, terms: false},
});
return (
<Form noValidate onSubmit={handleSubmit(async (v) => { await saveProfile(v); })}>
<Controller control={control} name="country" rules={{required: 'Choose a country'}} render={({field, fieldState}) => (
<Field label="Country" required error={fieldState.error?.message}>
<Combobox ref={field.ref} name={field.name} value={field.value} onValueChange={field.onChange} onBlur={field.onBlur} options={countries} placeholder="Search countries" />
</Field>
)} />
<Controller control={control} name="role" rules={{required: 'Choose a role'}} render={({field, fieldState}) => (
<Field label="Role" required error={fieldState.error?.message}>
<Select name={field.name} value={field.value} onValueChange={field.onChange}>
<SelectTrigger ref={field.ref} onBlur={field.onBlur}><SelectValue placeholder="Select a role" /></SelectTrigger>
<SelectContent>
<SelectItem value="admin">Admin</SelectItem>
<SelectItem value="editor">Editor</SelectItem>
</SelectContent>
</Select>
</Field>
)} />
<Controller control={control} name="start" rules={{validate: (d) => d !== null || 'Pick a start date'}} render={({field, fieldState}) => (
<Field label="Start date" required error={fieldState.error?.message}>
<DatePicker ref={field.ref} value={field.value} onValueChange={field.onChange} min={new Date()} />
</Field>
)} />
<Controller control={control} name="terms" rules={{validate: (v) => v || 'Accept the terms to continue'}} render={({field, fieldState}) => (
<Field label="Terms" error={fieldState.error?.message}>
<Checkbox ref={field.ref} checked={field.value} onCheckedChange={(c) => field.onChange(c === true)} label="I accept the terms" />
</Field>
)} />
<FormActions>
<Button type="submit" variant="solid" loading={isSubmitting}>Save profile</Button>
</FormActions>
</Form>
);
}
The same pattern for the other value components. Slider reports an array, so take the first item. OtpInput, Rating, Slider and SegmentedControl need an aria-label because they have no native label. RadioGroup belongs in a Fieldset with a legend, not a Field.
import {Controller, useForm} from 'react-hook-form';
import {Field, Fieldset, OtpInput, RadioGroup, RadioGroupItem, Rating, SegmentedControl, Slider, Switch} from '@monoline/react';
interface Values { code: string; billing: string; score: number; budget: number; view: string; alerts: boolean }
export function ControlledExamples() {
const {control} = useForm<Values>({defaultValues: {code: '', billing: 'monthly', score: 0, budget: 40, view: 'list', alerts: true}});
return (
<>
<Controller control={control} name="code" rules={{minLength: {value: 6, message: 'Enter all 6 digits'}}} render={({field, fieldState}) => (
<Field label="Verification code" error={fieldState.error?.message}>
<OtpInput aria-label="Verification code" length={6} value={field.value} onValueChange={field.onChange} invalid={!!fieldState.error} />
</Field>
)} />
<Controller control={control} name="billing" render={({field}) => (
<Fieldset legend="Billing">
<RadioGroup name={field.name} value={field.value} onValueChange={field.onChange}>
<RadioGroupItem value="monthly" label="Monthly" />
<RadioGroupItem value="yearly" label="Yearly" />
</RadioGroup>
</Fieldset>
)} />
<Controller control={control} name="score" rules={{min: {value: 1, message: 'Choose a rating'}}} render={({field, fieldState}) => (
<Field label="Rating" error={fieldState.error?.message}>
<Rating aria-label="Rating" value={field.value} onValueChange={field.onChange} />
</Field>
)} />
<Controller control={control} name="budget" render={({field}) => (
<Field label="Budget">
<Slider aria-label="Budget" min={0} max={100} step={5} value={field.value} onValueChange={(v) => field.onChange(v[0])} />
</Field>
)} />
<Controller control={control} name="view" render={({field}) => (
<Field label="Default view">
<SegmentedControl aria-label="Default view" value={field.value} onValueChange={field.onChange} options={[{value: 'list', label: 'List'}, {value: 'grid', label: 'Grid'}]} />
</Field>
)} />
<Controller control={control} name="alerts" render={({field}) => (
<Switch label="Email me about changes" checked={field.value} onCheckedChange={field.onChange} />
)} />
</>
);
}
Validation with Zod
Messages come from the schema, not the components. Pass the resolver and the rest of the code does not change: errors.email?.message and fieldState.error?.message keep feeding Field's error. Write messages as an instruction (“Enter your email”), as DESIGN.md asks of all copy.
import {useForm} from 'react-hook-form';
import {zodResolver} from '@hookform/resolvers/zod';
import {z} from 'zod';
const schema = z.object({
email: z.string().min(1, 'Enter your email').email('Enter an email like [email protected]'),
password: z.string().min(12, 'Use at least 12 characters'),
seats: z.number({message: 'Enter a number'}).int().min(1, 'At least one seat'),
});
type Values = z.infer<typeof schema>;
const form = useForm<Values>({resolver: zodResolver(schema), defaultValues: {email: '', password: '', seats: 5}});
// register('seats', {valueAsNumber: true}) keeps the value a number, so the schema sees a number.
Errors, summary and submit states
Show the message beside the field, and also list all of them at the top once the user has tried to submit. Form renders the summary as a role="alert" region; each link calls focus() on form.elements.namedItem(name), so it works for controls that carry that name (Input, Textarea, NativeSelect, NumberInput, and Combobox if you pass name). For Select and DatePicker use field.ref: with the default shouldFocusError, react-hook-form focuses the first invalid control after a failed submit.
import {Alert, Button, Field, Form, FormActions, Input, type FormError} from '@monoline/react';
// Inside the component from the first example:
const {register, handleSubmit, setError, formState: {errors, isSubmitting}} = useForm<Values>();
// 1. Build the summary from RHF's errors. Each "name" must match the control's name attribute.
const summary: FormError[] = Object.entries(errors).map(([name, e]) => ({name, message: e?.message ?? 'Check this field'}));
// 2. A failure from the server can be put on a field, or on the form.
const onSubmit = handleSubmit(async (values) => {
const res = await saveAccount(values);
if (res.status === 409) setError('email', {message: 'That email already has an account'});
else if (!res.ok) setError('root.server', {message: 'We could not save. Try again.'});
});
return (
<Form noValidate errors={summary} onSubmit={onSubmit}>
{errors.root?.server && <Alert tone="danger" title="Not saved">{errors.root.server.message}</Alert>}
<Field label="Email" required error={errors.email?.message}>
<Input type="email" {...register('email', {required: 'Enter your email'})} />
</Field>
<FormActions>
<Button type="submit" variant="solid" loading={isSubmitting}>Create account</Button>
</FormActions>
</Form>
);
isSubmittingis true while your asynconSubmitruns. Pass it toButton loading.- Keep the label on a loading button. Do not swap it for “Please wait”;
aria-busyalready carries the state. - Do not disable the submit button to signal an invalid form. Let the user submit and tell them what to fix.
Plain controlled state
No library is needed for a small form. Hold the values and errors in state, validate on submit, and pass the same props. Here Form preventDefault stops the native post, and the name on each input lets the summary links find it.
import {useState, type FormEvent} from 'react';
import {Button, Field, Form, FormActions, Input, type FormError} from '@monoline/react';
type Errors = Record<string, string>;
const validate = (email: string, password: string): Errors => {
const e: Errors = {};
if (!email) e.email = 'Enter your email';
else if (!/^\S+@\S+\.\S+$/.test(email)) e.email = 'Enter an email like [email protected]';
if (password.length < 12) e.password = 'Use at least 12 characters';
return e;
};
export function PlainForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState<Errors>({});
const [busy, setBusy] = useState(false);
const submit = async (_e: FormEvent<HTMLFormElement>) => {
const next = validate(email, password);
setErrors(next);
if (Object.keys(next).length) return;
setBusy(true);
try { await saveAccount({email, password}); } finally { setBusy(false); }
};
const summary: FormError[] = Object.entries(errors).map(([name, message]) => ({name, message}));
return (
<Form noValidate preventDefault errors={summary} onSubmit={submit}>
<Field label="Email" required error={errors.email}>
<Input name="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</Field>
<Field label="Password" required error={errors.password}>
<Input name="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</Field>
<FormActions><Button type="submit" variant="solid" loading={busy}>Create account</Button></FormActions>
</Form>
);
}
TanStack Form
The same props apply. Wire field.state.value, field.handleChange and field.handleBlur to a Monoline control, and field.state.meta.errors to Field error. This follows the TanStack Form v1 API and has not been run here; for Controller-style components use onValueChange={field.handleChange}.
import {useForm} from '@tanstack/react-form';
import {Button, Field, Form, FormActions, Input} from '@monoline/react';
export function TanStackExample() {
const form = useForm({
defaultValues: {email: ''},
onSubmit: async ({value}) => { await saveAccount(value); },
});
return (
<Form noValidate preventDefault onSubmit={() => { void form.handleSubmit(); }}>
<form.Field
name="email"
validators={{onBlur: ({value}) => (value ? undefined : 'Enter your email')}}
children={(field) => (
<Field label="Email" required error={field.state.meta.isTouched ? field.state.meta.errors.join(', ') || undefined : undefined}>
<Input name={field.name} type="email" value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.target.value)} />
</Field>
)}
/>
<FormActions>
<form.Subscribe selector={(s) => s.isSubmitting} children={(busy) => <Button type="submit" variant="solid" loading={busy}>Create account</Button>} />
</FormActions>
</Form>
);
}