@conform-to/zod
Zod schema resolver for conform
API Reference
resolve
This resolves zod schema to a conform schema:
import { useForm, useFieldset } from '@conform-to/react';
import { resolve } from '@conform-to/zod';
import { z } from 'zod';
const schema = resolve(
z.object({
email: z.string(),
password: z.string(),
})
);
function ExampleForm() {
const formProps = useForm({
validate: schema.validate
onSubmit: event => {
const payload = new FormData(e.target);
const submission = schema.parse(payload);
console.log(submission.state);
console.log(submission.data);
console.log(submission.form.value);
console.log(submission.form.error);
};
})
const [setupFieldset, { email, password }] = useFieldset({
constraint: schema.constraint
});
}
Or parse the request payload on server side (e.g. Remix):
import { resolve } from '@conform-to/zod';
import { z } from 'zod';
const schema = resolve(
z.object({
}),
);
export let action = async ({ request }) => {
const formData = await request.formData();
const submission = schema.parse(formData);
if (submission.state !== 'accepted') {
return json(submission.form);
}
};
export default function ExampleRoute() {
const formState = useActionData();
}
ifNonEmptyString
As zod
does not have specific logic for handling form data, there are some common cases need to be handled by the users. For example,
- it does not treat empty string as invalid for a requried field
- it has no type coercion support (e.g. '1' -> 1)
The zod schema resolver currently does an extra cleanup step to transform empty string to undefined internally. But users are still required to do convert the data to their desired type themselves.
import { z } from 'zod';
import { resolve, ifNonEmptyString } from '@conform-to/zod';
const schema = resolve(
z.object({
text: z.string({ required_error: 'This field is required' }),
number: z.preprocess(
ifNonEmptyString(Number),
z.number({ required_error: 'This field is required' }),
),
date: z.preprocess(
(value) => (typeof value === 'string' ? new Date(value) : value),
z.date({ required_error: 'This field is required' }),
),
}),
);