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] Yup-like shotcut methods in the main z object #3928

Open
LonguCodes opened this issue Dec 29, 2024 · 1 comment
Open

[Feature request] Yup-like shotcut methods in the main z object #3928

LonguCodes opened this issue Dec 29, 2024 · 1 comment

Comments

@LonguCodes
Copy link

LonguCodes commented Dec 29, 2024

Currenty, the only way to create a shortcut is to create a function and wrap the schema inside it.

function emptyOrOptional(schema: ZodString): ZodString {
   return z.union([schema.optional(), z.string().max(0)]);
}

const validationSchema = emptyOrOptional(z.string().email())

This results in 2 different sytanxes, chaining and wrapping.

Would it be possible to create something similar to yup's addMethod, which would result in following code?

z.addMethod('emptyOrOptional',<params>);

const validationSchema = z.string().email().emptyOrOptional()
@LonguCodes
Copy link
Author

This is achievable using typescript and some prototype pollution

// zod-custom.d.ts

export * from 'zod';
declare module 'zod' {
  interface ZodString {
    allowEmpty(): ZodString;
  }
}

// zod-custom.ts

import { z, ZodString } from 'zod';

z.ZodString.prototype['allowEmpty'] = function () {
  return this.or(z.string().max(0)) as unknown as ZodString;
};

Maybe documentation would be enough in this case

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

1 participant