shadcn.io is not affiliated with official shadcn/ui
Form examples · Validation
Conditional Validation Form for React
A form whose company fields appear, and whose company name becomes required, only once the I have a company box is checked.
Not every field applies to everyone. Checking I have a company reveals Company Name and Company Website, and a Zod refine on the whole object makes the name required only while the box is checked. useWatch reads the checkbox's value to show or hide the two Fields, and a Controller wires each control into React Hook Form. Use it for optional sections, progressive disclosure, or any form whose rules depend on an earlier answer.
Preview
Installation
FAQ
How do the company fields appear?
useWatch({ control: form.control, name: "hasCompany" }) returns the checkbox's current value, and the Company Name and Company Website fields render only while it's true. The box starts unchecked from defaultValues.
How is the checkbox connected?
A horizontal Field holds the Checkbox, then a FieldContent with the label I have a company and the description "Check this if you represent a company." checked={field.value} and onCheckedChange={field.onChange}.
When is the company name required?
The schema's refine passes when hasCompany is false, or when companyName has at least 2 characters. Otherwise it fails with "Company name is required" on path: ["companyName"], so the error lands in that field's FieldError.
What does the website field accept?
companyWebsite is z.url().optional().or(z.literal("")): empty passes, anything else has to be a URL, and a bad one shows Zod's default "Invalid URL". The label says Company Website (Optional).
Related
- Form with Optional FieldsA form with required name and email
- Required Field Validation FormA name and an email field marked with
- Custom Validation Messages FormA sign-up form whose username, email and
- Simple Checkbox FieldA terms and conditions checkbox with its
- Form with Field GroupsA form split into Personal Information
- Email Validation FormAn email field and a confirm email field