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.
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
Installation
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.
Related
- Simple Text Input FormA form with one username text input that
- Phone Input FormA phone number form that checks the
- Number Input with ControlsA quantity field between minus and plus
- Simple Slider FieldA volume slider whose description shows
- Simple Input with Label FieldAn email input with its label above it
- Range Slider FieldA two-thumb price range slider whose