Form Validation

    You must validate data on the server and also on the client before sending data to the server

    For validation we are using zod read their documentation for full explanation but in short most of the time you will do something like this

    1. Create validation schema in /src/utils/validation.ts

    /src/utils/validation.ts

    export const mySchema = z.object({
      message: z.string().min(1).max(100),
    });
    
    1. On the client add it to a useForm from react-hook-form

    /src/app/example-page/page.tsx

    "use client";
    
    import { mySchema } from "utils/validation";
    import { zodResolver } from "@hookform/resolvers/zod";
    import { z } from "zod";
    import {
      Form,
      FormControl,
      FormField,
      FormItem,
      FormMessage,
    } from "components/ui/form";
    
    type Schema = z.infer<typeof mySchema>;
    
    const ExamplePage = () => {
      const form = useForm<Schema>({
        defaultValues: { message: "" },
        resolver: zodResolver(orderNoteSchema),
      });
    
      return (
        <Form {...form}>
          <FormField
            control={form.control}
            name="message"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Textarea placeholder="message..." {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
    
          <Button isLoading={isPending} type="submit" className="w-full">
            Add Message
          </Button>
        </Form>
      );
    };
    
    export default ExamplePage;
    
    1. On the server you can validate the received data like this

    /src/app/api/example_endpoint/route.ts

    import { mySchema } from "utils/validation";
    
    export const POST = (request) => {
      const { success, error, data } = mySchema.safeParse(await req.json());
      if (!success) {
        // do something - usually throw an error
      }
      // rest of the code
    };