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

[Feature Request] store validator function for z.refine #3430

Closed
soc221b opened this issue Apr 22, 2024 · 1 comment
Closed

[Feature Request] store validator function for z.refine #3430

soc221b opened this issue Apr 22, 2024 · 1 comment

Comments

@soc221b
Copy link
Contributor

soc221b commented Apr 22, 2024

Hi, thank you for building this powerful validation library~

Feature Request

Could we store the user-defined validator in somewhere like schema._def.effect:

https://github.com/colinhacks/zod/blob/890556e/src/types.ts#L322

Use case

I'm implementing a zod-schema-faker library to generate fake data for zod.

Recently I am trying to support fake data generation for custom schema (.custom) and custom validation logic (.refine), the strategy is to identify the schema/validator and execute user-defined faker to achieve the goal.

For example:

// user may have this validator:
const validator = (val: string) => val.length <= 255
const schema = z.string().refine(validator, {
  message: "String can't be more than 255 characters",
})

// they could generate data by register a custom validator:
function validatorFaker(fakeVal: string): string {
  return fakeVal.slice(0, 255)
}
installRefine(validator, validatorFaker)
const fakeData = fake(schema)

Further info about how custom schema to be supported:

import * as z from 'zod'
import { fake, installCustom, ZodTypeFaker, runFake, install } from 'zod-schema-faker'

const pxSchema = z.custom<`${number}px`>(val => {
  return typeof val === 'string' ? /^\d+px$/.test(val) : false
})

class pxFaker extends ZodTypeFaker<typeof pxSchema> {
  fake(): `${number}px` {
    return `${runFake(faker => faker.number.int({ min: 0 }))}px`
  }
}
install()
installCustom(pxSchema, pxFaker)
const data = fake(pxSchema)
// > '10px'

Thank you 😄

@colinhacks
Copy link
Owner

Yes! This is the plan for Zod 4.

@soc221b soc221b closed this as completed Apr 23, 2024
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

2 participants