Zod Schema / parseWithZod

parseWithZod

A helper that returns an overview of the submission by parsing the form data with the provided zod schema.

1const submission = parseWithZod(payload, options);

#Parameters

payload

It could be either the FormData or URLSearchParams object depending on how the form is submitted.

options.schema

Either a zod schema or a function that returns a zod schema.

options.async

Set it to true if you want to parse the form data with safeParseAsync method from the zod schema instead of safeParse.

options.errorMap

A zod error map to be used when parsing the form data.

options.formatError

A function that let you customize the error structure and include additional metadata as needed.

options.disableAutoCoercion

Set it to true if you want to disable automatic type coercion and manage how the form data is parsed yourself.

#Example

1import { parseWithZod } from '@conform-to/zod';
2import { useForm } from '@conform-to/react';
3import { z } from 'zod';
4
5const schema = z.object({
6  email: z.string().email(),
7  password: z.string(),
8});
9
10function Example() {
11  const [form, fields] = useForm({
12    onValidate({ formData }) {
13      return parseWithZod(formData, { schema });
14    },
15  });
16
17  // ...
18}

#Tips

Automatic type coercion

By default, parseWithZod will strip empty value and coerce form value to the correct type by introspecting the schema and inject extra preprocessing steps using the coerceFormValue helper internally.

If you want to customize this behavior, you can disable automatic type coercion by setting options.disableAutoCoercion to true and manage it yourself.

1import { parseWithZod } from '@conform-to/zod';
2import { useForm } from '@conform-to/react';
3import { z } from 'zod';
4
5const schema = z.object({
6  // Strip empty value and coerce the number yourself
7  amount: z.preprocess((value) => {
8    if (typeof value !== 'string') {
9      return value;
10    }
11
12    if (value === '') {
13      return undefined;
14    }
15
16    return Number(value.trim().replace(/,/g, ''));
17  }, z.number()),
18});
19
20function Example() {
21  const [form, fields] = useForm({
22    onValidate({ formData }) {
23      return parseWithZod(formData, {
24        schema,
25        disableAutoCoercion: true,
26      });
27    },
28  });
29
30  // ...
31}