-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Shorter way to validate boolean from string "true" / "false" / overwrite a schema #1055
Comments
I’d use import { z } from 'zod'
const stringToBoolean = (value: unknown) => {
switch (value) {
case "true":
case "TRUE":
case "1":
return true
case "false":
case "FALSE":
case "0":
return false
default:
return undefined
}
}
const schema = z.preprocess(stringToBoolean, z.boolean()).optional() And then just put your utility functions like If that’s still too much, you could even put a const booleanStringSchema = z.preprocess(stringToBoolean, z.boolean()) into e.g. const environmentVariablesSchema = z.object({
NO_COLOR: booleanStringSchema.optional(),
USE_TLS: booleanStringSchema.default(false),
}) |
Coherent diskussion: #804 @FlorianWendelborn Thx, had some similar solution. |
Please see coercion: https://github.com/colinhacks/zod#coercion-for-primitives |
@ryanhaticus coercion is likely not a good idea here since it's literally just a I'd personally still recommend using a preprocess utility similar to the one I posed above as it doesn't have these unexpected behaviors, so no need to re-open this ticket |
e.g. you call a rest-api endpoint with
//some/endpoint?isVisible=true
The server receives a string
isVisible = 'true'
How you validate it in a shorter way?
Is there a way to extend / overwrite z.boolean?
The text was updated successfully, but these errors were encountered: