zod
zod copied to clipboard
Error message based on input value
I need to generate error message based on the input value, now I have to use errorMap which is tedious.
I hope I can write code like this:
z
.string({ invalid_type_error: value => 'Expected a string, received: ' + String(value) })
.min(2, { message: value => 'Expected a string with at least 2 characters, received: ' + String(value) })
Is this what you are looking for?
const schema = z.string( {
errorMap: ( issue, ctx ) => {
switch ( issue.code ) {
case 'invalid_type': return {
message: `Expected a string, received: ${ ctx.data }`
}
case 'too_small': return {
message: `Expected a string with at least ${ issue.minimum } characters, received: ${ ctx.data }`
}
default: return {
message: ctx.defaultError
}
}
}
} ).min( 2 )
const result1 = schema.safeParse( 42 )
!result1.success && console.log( result1.error.issues )
// [
// {
// code: "invalid_type",
// expected: "string",
// received: "number",
// path: [],
// message: "Expected a string, received: 42"
// }
// ]
const result2 = schema.safeParse( 'a' )
!result2.success && console.log( result2.error.issues )
// [
// {
// code: "too_small",
// minimum: 2,
// type: "string",
// inclusive: true,
// exact: false,
// message: "Expected a string with at least 2 characters, received: a",
// path: []
// }
// ]
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 https://github.com/sponsors/JacobWeisenburger
Is this what you are looking for?
This is possible, but annoying to write. I just want to write those error inline.
I need to generate error message based on the input value, now I have to use errorMap which is tedious.
I hope I can write code like this:
z .string({ invalid_type_error: value => 'Expected a string, received: ' + String(value) }) .min(2, { message: value => 'Expected a string with at least 2 characters, received: ' + String(value) })
I Agree with you as I'm also looking for exactly the same thing as having your own custom errors is super helpful. I hope they do this soon but have you found any better approach or way of doing the same thing which you've requested?
I can work on that! @JacobWeisenburger
I think something like this should definitely happen, but it won't look exactly like this. This will land in Zod 4. More details here https://github.com/colinhacks/zod/pull/3152#issuecomment-1945200427 Leaving open for now.
This would also be quite valuable for i18n use-cases, since the language of the error-message usually needs to be determined the moment parsing happens instead of upfront when the module loads.