Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Form examples · Multi Field

Form with Optional Fields for React

A form with required name and email fields and optional company and website fields marked in their labels.

Framework
UI library

Not every field deserves to be required. This form requires a first name, a last name and an email, and leaves company and website optional, saying so in their labels. The Zod schema makes company .optional() and lets website be a valid URL or an empty string. Names share a two-column grid, and each field is a Field with its FieldLabel, Input and FieldError. Use it for flexible registration, profile updates or contact forms.

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

Which fields are required?

firstName and lastName need at least 2 characters, with "First name must be at least 2 characters." and "Last name must be at least 2 characters." email is z.email(…) with "Please enter a valid email address."

Why can company be left blank?

company is z.string().optional() with no length rule, so an empty string passes. Its label reads Company (Optional) and its description asks "Where do you work?"

What website values pass?

website is z.url().optional().or(z.literal("")): an empty string or a full URL such as https://example.com. Anything else gets Zod's default URL message.

Which fields have a description?

Company ("Where do you work?") and website ("Your personal or company website."). The required fields have a label, the input and a FieldError.

How are the optional inputs registered?

Like the others: a Controller per field, the input takes field, and the Field gets invalid={fieldState.invalid}. defaultValues starts every field at an empty string. Each label's htmlFor matches its input's id, such as form-with-optional-fields-website.

What does Save log?

Save is a type="submit" button. Once the required fields pass, onSubmit logs all five values, with empty strings for skipped optional fields.