← All Demos Form Single-page form example built with Spar components and React Hook Form. Submit stays available, but when validation fails focus moves to the first invalid field. Success and error feedback are announced with an alert, and the code example is shown alongside the live form.
// 1. shouldFocusError: true — RHF focuses the first
// invalid field automatically on submit.
const { register, control, handleSubmit,
formState: { errors } } = useForm({
mode: 'onChange',
shouldFocusError: true,
});
// 2. register with rules — RHF handles native inputs.
<Field required invalid={!!errors.fullName}>
<Field.Label>Full name *</Field.Label>
<Input>
<Input.Field
{...register('fullName', {
required: true,
validate: (v) => v.trim().length > 0,
})}
/>
</Input>
</Field>
// 3. Controller + field.ref — lets RHF focus custom
// components (Select, Checkbox) on validation error.
<Controller name='role' rules={{ required: true }}
render={({ field }) => (
<Select.Root value={field.value}
onChange={(v) => {
field.onChange(v);
field.onBlur();
}}>
<Select.Trigger ref={field.ref} placeholder='Select a role…' />
</Select.Root>
)}
/>
<Controller name='terms'
rules={{ validate: (v) => v === true }}
render={({ field: { ref, value, onChange } }) => (
<Checkbox ref={ref} checked={value} onChange={onChange}>
{({ checked }) => checked ? '✓' : ''}
</Checkbox>
)}
/>
// 4. onSubmit only runs on success — no manual checks.
const onSubmit = (data) => {
setSubmittedMessage(`Submitted: ${data.plan}`);
};
// Error display via formState.errors:
{errors.role && <div role='alert'>Role is required</div>}
{errors.terms && <div role='alert'>Accept terms to submit</div>}