Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Form examples · Basic Forms

Number Input Form for React

An age form with one number input that only submits ages from 18 to 120.

Framework
UI library

Age gates need a number, but an input's value is a string. This form converts the value in the input's change handler, so React Hook Form holds a number (or undefined when the box is empty), and the Zod schema checks it with z.number(), a minimum of 18 and a maximum of 120. The Input sits in a Field with a FieldDescription for the rule and a FieldError for the message. Use it for age checks, quantities or any number with a range.

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 does the string become a number?

The Controller doesn't spread field here. The Input's onChange passes undefined for an empty box and Number(event.target.value) otherwise, and value is field.value ?? "". The schema is z.number() with .min(18, "You must be at least 18 years old.") and .max(120, "Please enter a valid age.").

What happens if age is left blank?

defaultValues sets age to undefined, and clearing the box sets it back. undefined isn't a number, so submit fails with "You must be at least 18 years old.", the message passed to z.number().

What does type number change?

The Input sets type="number" and the placeholder 25, so phones show a numeric keyboard and the browser only lets numbers in. It also passes name, onBlur and ref from field so React Hook Form can track and focus it.

Where is the age rule explained before submit?

FieldDescription says "You must be 18 or older to continue." FieldError below it shows the minimum or maximum message after a failed submit.

What does Verify Age submit?

Verify Age is a type="submit" button. form.handleSubmit(onSubmit) runs the schema and calls onSubmit with age as a number, which the demo logs.

When do the min and max checks run?

mode is unset, so they first run on submit. After a failed submit, React Hook Form checks again as the number changes, and the error clears once the age is in range.