Loading...
Loading...
> Building forms with react-hook-form and zod validation. Provides automatic validation, error handling, and accessibility.
1import {2 Form,3 FormControl,4 FormDescription,5 FormField,6 FormItem,7 FormLabel,8 FormMessage,9} from "@/components/ui/form";10import { useForm } from "react-hook-form";11import { zodResolver } from "@hookform/resolvers/zod";12import * as z from "zod";
1const formSchema = z.object({2 username: z.string().min(3, "Username must be at least 3 characters"),3 email: z.string().email("Invalid email address"),4});56function Example() {7 const form = useForm<z.infer<typeof formSchema>>({8 resolver: zodResolver(formSchema),9 defaultValues: {10 username: "",11 email: "",12 },13 });1415 const onSubmit = (_values: z.infer<typeof formSchema>) => {16 // Handle form submission17 };1819 return (20 <Form {...form}>21 <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">22 <FormField23 control={form.control}24 name="username"25 render={({ field }) => (26 <FormItem>27 <FormLabel>Username</FormLabel>28 <FormControl>29 <Input placeholder="johndoe" {...field} />30 </FormControl>31 <FormDescription>Your public display name.</FormDescription>32 <FormMessage />33 </FormItem>34 )}35 />36 <FormField37 control={form.control}38 name="email"39 render={({ field }) => (40 <FormItem>41 <FormLabel>Email</FormLabel>42 <FormControl>43 <Input type="email" placeholder="john@example.com" {...field} />44 </FormControl>45 <FormMessage />46 </FormItem>47 )}48 />49 <Button type="submit">> SUBMIT</Button>50 </form>51 </Form>52 );53}
1<Form {...form}>2 <form onSubmit={form.handleSubmit(onSubmit)}>3 <FormField4 control={form.control}5 name="fieldName"6 render={({ field }) => (7 <FormItem>8 <FormLabel>Label</FormLabel>9 <FormControl>10 <Input {...field} />11 </FormControl>12 <FormDescription>Description</FormDescription>13 <FormMessage />14 </FormItem>15 )}16 />17 </form>18</Form>
1const formSchema = z.object({2 username: z3 .string()4 .min(3, "Username must be at least 3 characters")5 .max(20, "Username must not exceed 20 characters"),6 email: z7 .string()8 .email("Invalid email address"),9 password: z10 .string()11 .min(12, "Password must be at least 12 characters")12 .regex(/[A-Z]/, "Must contain uppercase letter")13 .regex(/[0-9]/, "Must contain a number"),14});
| Prop | Type | Default | Description |
|---|---|---|---|
| control | Control<TFieldValues> | - | Form control object from useForm hook. |
| name | FieldPath<TFieldValues> | - | Name of the field in the form schema. |
| render | ({ field }) => ReactElement | - | Render function that receives field props. |