colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.92k stars 1.18k forks source link

Feature: support multiple parameters in `.startsWith()` #3683

Open jansepke opened 3 months ago

jansepke commented 3 months ago

Currently it quite verbose to define a string that can start with multiple different prefixes:

const schema = z
  .string()
  .startsWith('foo_')
  .or(z.string().startsWith('bar_'))
  .or(z.string().startsWith('baz_'));

it would be great if .startsWith() would support an array of strings like

const schema = z
  .string()
  .startsWith(['foo_', 'bar_', 'baz_']);

maybe I am also missing an alternative solution for the problem.

tristinDLC commented 3 months ago

You can do it cleaner with regex:

const schema = z
    .string()
    .regex(/^foo_|bar_|baz_/)

I'll admit that using .startsWith() is a bit better because you can quickly see what it's intended to do, but the regex pattern will functionally cover your use-case.

jansepke commented 3 months ago

@tristinDLC yes I know, but using regex always hides the intention. But I would also close this issue if this would add too much complexity for not enough value to zod.

Kumar06Lav commented 3 months ago

I've submitted a PR to add support for multiple parameters in the .startsWith() and .endsWith() methods for string validation.