Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Form examples · Validation

Min/Max Length Validation Form for React

A username of 3 to 20 characters and a bio of 10 to 160, with a live character count under the bio.

Framework
UI library

Nobody wants to type 200 characters and then find out the limit is 160. Zod's .min and .max hold the username to 3–20 characters and the bio to 10–160, and the bio's FieldDescription counts characters as you type. Each input is a Field wired to React Hook Form by a Controller, with a FieldError for the length messages. Use it for usernames, bios, or any length-limited text.

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

What length is the username held to?

.min(3, "Username must be at least 3 characters") and .max(20, "Username must not exceed 20 characters"). Its FieldDescription says "3-20 characters required." and the FieldError shows whichever rule fails.

What length is the bio held to?

.min(10, "Bio must be at least 10 characters") and .max(160, "Bio must not exceed 160 characters"). Bio is a single-line Input, not a textarea, with the placeholder "Tell us about yourself".

How does the 160 counter update?

The bio's FieldDescription prints field.value.length after "10-160 characters.", so it follows every keystroke. The length messages still wait for Save, because mode is the default, on submit.

What are the starting strings?

defaultValues sets bio and username to "", so the counter starts at 0/160 and an empty submit fails both minimums.

How are the fields registered?

Each field is a Controller with control={form.control} and its name, which spreads field onto the Input and passes fieldState.invalid to the Field. The resolver is zodResolver(formSchema).

What does Save log?

Save is a type="submit" button. Once both lengths are in range, onSubmit logs { bio, username } to the console.