Command Palette

Search for a command to run...

Form

Building forms with React Hook Form and Zod schema validation.

This is your public display name.

Installation

npm install react-hook-form @hookform/resolvers zod

Usage

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 import { useForm } from "react-hook-form" import { zodResolver } from "@hookform/resolver/zod" import * as z from "zod" import { Button } from "@/components/ui/button" import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" const formSchema = z.object({ username: z.string().min(2, { message: "Username must be at least 2 characters.", }), }) export function ProfileForm() { const form = useForm<z.infer<typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues: { username: "", }, }) function onSubmit(values: z.infer<typeof formSchema>) { console.log(values) } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormLabel>Username</FormLabel> <FormControl> <Input placeholder="shadcn" {...field} /> </FormControl> <FormDescription> This is your public display name. </FormDescription> <FormMessage /> </FormItem> )} /> <Button type="submit">Submit</Button> </form> </Form> ) }

Examples

Form Validation

You must be at least 18 years old.

Field Array

Form Components

ComponentDescription
FormThe main wrapper component that provides form context from react-hook-form.
FormFieldA component that provides context for form fields.
FormItemContains and provides context for form elements.
FormLabelAn accessible label for form controls.
FormControlA component that wraps form controls and provides accessibility attributes.
FormDescriptionA description component for providing additional information about a form field.
FormMessageDisplays validation errors for form fields.