coerceFormValue
The
coerceFormValuefunction is part of Conform's future export. These APIs are experimental and may change in minor versions. Learn more
A helper that enhances the schema with extra preprocessing steps to strip empty values and coerce form values to the expected type. To customize the coercion behavior, use configureCoercion.
import { coerceFormValue } from '@conform-to/zod/v3/future'; // Or '@conform-to/zod/v4/future'
const enhancedSchema = coerceFormValue(schema);The following rules are applied by default:
- If the value is an empty string / file, pass
undefinedto the schema - If the schema is
z.number(), trim the value and cast it with theNumberconstructor - If the schema is
z.boolean(), treat the value astrueif it equalson(browser defaultvalueof a checkbox / radio button) - If the schema is
z.date(), cast the value with theDateconstructor - If the schema is
z.bigint(), trim the value and cast it with theBigIntconstructor
#Parameters
schema
The zod schema to be enhanced.
#Example
import { coerceFormValue } from '@conform-to/zod/v3/future'; // Or '@conform-to/zod/v4/future'
import { useForm } from '@conform-to/react/future';
import { z } from 'zod';
const schema = coerceFormValue(
z.object({
ref: z.string(),
date: z.date(),
amount: z.number(),
confirm: z.boolean(),
}),
);
function Example() {
const { form, fields } = useForm(schema, {
// ...
});
// ...
}#Tips
Default values
coerceFormValue will always strip empty values to undefined. If you need a default value, use .transform() to define a fallback value that will be returned instead.
const schema = z.object({
foo: z.string().optional(), // string | undefined
bar: z
.string()
.optional()
.transform((value) => value ?? ''), // string
baz: z
.string()
.optional()
.transform((value) => value ?? null), // string | null
});