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/valibot/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
v.number(), trim the value and cast it with theNumberconstructor - If the schema is
v.boolean(), treat the value astrueif it equalson(browser defaultvalueof a checkbox / radio button) - If the schema is
v.date(), cast the value with theDateconstructor - If the schema is
v.bigint(), trim the value and cast it with theBigIntconstructor
#Parameters
schema
The valibot schema to be enhanced.
#Example
import { coerceFormValue } from '@conform-to/valibot/future';
import { useForm } from '@conform-to/react/future';
import * as v from 'valibot';
const schema = coerceFormValue(
v.object({
ref: v.string(),
date: v.date(),
amount: v.number(),
confirm: v.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 optional() to define a fallback value that will be returned instead.
const schema = v.object({
foo: v.optional(v.string()), // string | undefined
bar: v.optional(v.string(), ''), // string
baz: v.optional(v.nullable(v.string()), null), // string | null
});