Skip to content
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

Closed
rottmann opened this issue Mar 29, 2022 · 4 comments

Comments

@rottmann
Copy link

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?

const isVisibleSchema = z.union([ z.literal('true'), z.literal('false') ]).optional().transform( (val) => val === 'true') // overkill

const humanReadableWouldBe = z.boolean().optional() // not work, cause it is a string

Is there a way to extend / overwrite z.boolean?

@FlorianWendelborn
Copy link
Contributor

FlorianWendelborn commented Mar 29, 2022

I’d use z.preprocess for this. Just do:

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 stringToBoolean into a dedicated file. E.g. utilities/zod-preprocess.ts

If that’s still too much, you could even put a

const booleanStringSchema = z.preprocess(stringToBoolean, z.boolean())

into e.g. utilities/schemas and then just reference it whenever you need it:

const environmentVariablesSchema = z.object({
    NO_COLOR: booleanStringSchema.optional(),
    USE_TLS: booleanStringSchema.default(false),
})

@rottmann
Copy link
Author

Coherent diskussion: #804

@FlorianWendelborn Thx, had some similar solution.

@ryanhaticus
Copy link

@FlorianWendelborn
Copy link
Contributor

@ryanhaticus coercion is likely not a good idea here since it's literally just a Boolean cast. Here's one example where it likely produces the opposite of what you'd expect in the API proposed by OP

image

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants