Configurable preprocess (transform) of values #387
Replies: 2 comments 4 replies
-
Conform strips the empty string and does type coercion by introspecting the complete schema and inject extra preprocess step on each field: // Let's say this is the schema you have:
const schema = z.object({
number: z.number(),
});
// Conform turns it to this:
const schema = z.object({
number: z.preprocess(value => {
if (typeof value !== 'string') {
// Return the value as is if the value is not string
return value;
}
if (value === '') {
// Strip empty string
return undefined;
}
// Type coercion
return Number(value);
}, z.number()),
});
// If you add your own preprocess in the schema, like this:
const schema = z.object({
number: z.preprocess(value => {
// your custom preporcess logic
}, z.number()),
});
// Then it will become this:
const schema = z.object({
number: z.preprocess(value => {
// your custom preporcess logic
}, z.preprocess(value => {
if (typeof value !== 'string') {
// Return the value as is if the value is not string
return value;
}
if (value === '') {
// Strip empty string
return undefined;
}
// Type coercion
return Number(value);
}, z.number()),
}); As your preprocess will run first, you should be able to do whatever you want. |
Beta Was this translation helpful? Give feedback.
-
Haha, Conform already does this, and This also means that this works to transform empty strings/files to string: z.string().nullable().default(null),
file: z.instanceof(File).nullable().default(null), This all ended up being much easier than I expected! |
Beta Was this translation helpful? Give feedback.
-
I'd like to see the
@conform-to/zod
form data parser accept some sort of configuration where I can pass in my owntransform
and/orpreprocess
functions to replace the value coercion that is currently built in.For example, I'd prefer to
preprocess
empty strings and empty files toundefined
so my schemas could simply use.required()
checks for these types.Beta Was this translation helpful? Give feedback.
All reactions