JacobWeisenburger / zod_utilz

Framework agnostic utilities for Zod
MIT License
158 stars 9 forks source link

errorMap never work for refine #8

Closed issam-seghir closed 7 months ago

issam-seghir commented 7 months ago
const PortRefineErrorMap = zu.makeErrorMap({
    custom: (err) => `${err.data} is not a valid port number. Must be a number between 0 and 65536`,
});

const envSchema = z.object({
    PORT: z
        .string({ errorMap })
        .min(1, { message: "must not be empty" })
        .regex(numberRegex, { message: "must be a number" })
        .default("3000")
        .refine((num) => num > 0 && num < 65_536, { errorMap: PortRefineErrorMap })
        .transform((num) => Number.parseInt(num))
)}

try {
    const ENV = envSchema.parse({ PORT: "" });
} catch(err){
    ....
    log.error(`* ${err.path.join(".")}:`, `${err.message}`);
}
JacobWeisenburger commented 7 months ago

You can't pass an errorMap to refine normally.

const schema = z.string().refine( ( x ): x is string => true, {
    errorMap: () => ( { message: 'This is a custom error message' } )
    // ^^^^^
    // Object literal may only specify known properties, and 'errorMap' does not exist in type 'Partial<Omit<ZodCustomIssue, "code">>...
} )

Please pass the errorMap to z.string instead as is shown below and in the docs:

https://github.com/JacobWeisenburger/zod_utilz#makeerrormap

const errorMap = zu.makeErrorMap( {
    custom: ( err ) => `${ err.data } is not a valid port number. Must be a number between 0 and 65536`,
} )
const schema = z.string( { errorMap } )

If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 https://github.com/sponsors/JacobWeisenburger