Skip to content
shadcn.io

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.

Framework
UI library

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

Preview width

Installation

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

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).

Does hiding the fields drop their values?

No. Unchecking the box only stops rendering them; their values stay in the form. A website that isn't a URL still fails on submit, while the name rule stops applying once hasCompany is false.

What does Submit log?

Submit is a type="submit" button. On submit, form.handleSubmit(onSubmit) runs the schema and the refine, then logs { companyName, companyWebsite, hasCompany } to the console.