zod icon indicating copy to clipboard operation
zod copied to clipboard

add custom error message on nativeEnum validation

Open fernandollisboa opened this issue 1 year ago • 1 comments

Resolves #2919

Return invalid_type_error on nativeEnum validations instead of Invalid enum value when the attribute is set.

const schema = z.nativeEnum({ MY_ENUM: "MY_ENUM" }, {
  invalid_type_error: "the value provided is invalid",
})

console.log("result", schema.parse("AAA"));
// returns error "the value provided is invalid"

fernandollisboa avatar Jan 18 '24 22:01 fernandollisboa

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 9bd71f3bdd3343f2ea1398eb55570540d84dff70
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/65d44426557a55000894160a
Deploy Preview https://deploy-preview-3158--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

netlify[bot] avatar Jan 18 '24 22:01 netlify[bot]

Is there an update on this? Currently working with a list of US States as a native enum, having Zod throw out an error "Invalid string, expected one of <list of all 50 states>" doesn't make for the greatest user experience.

scarabcoder avatar Apr 04 '24 18:04 scarabcoder

@scarabcoder i believe they're working on a fix to be released on Zod 4: https://github.com/colinhacks/zod/issues/3146#issuecomment-1995968936

fernandollisboa avatar Apr 09 '24 15:04 fernandollisboa

My preferred solution here is the one that landed in #3169, which will land in Zod 3.23 shortly.

This is all liable to change in Zod 4 as well.

colinhacks avatar Apr 20 '24 22:04 colinhacks