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

Proposal: z.not(parser) or equivalent #2862

Open
rossipedia opened this issue Oct 12, 2023 · 4 comments
Open

Proposal: z.not(parser) or equivalent #2862

rossipedia opened this issue Oct 12, 2023 · 4 comments
Labels
enhancement New feature or request

Comments

@rossipedia
Copy link

Purpose:

Returns the inverse of the parser that is passed. For example:

// accepts anything _except_ a `string`.
z.not(z.string()) 

// accepts any string that _isn't_ an email
z.string().not(z.string().email());

Would this be useful? Is there a way of doing this in standard zod that I'm missing?

I know I can use refine(), but the ergonomics there are a bit awkward:

z.string().refine((val) => !z.string().email().safeParse(val).success);
@JacobWeisenburger JacobWeisenburger added the enhancement New feature or request label Oct 14, 2023
@JGJP
Copy link

JGJP commented Nov 3, 2023

I think this could be useful. The typescript equivalent would be doing a T extends string ? never : T I imagine. I think your second example would look better as:

z.not(z.string().email())

There should be a smart way to write your own utility function that replicates the behavior of z.not in this case

@colinhacks
Copy link
Owner

It's a nice idea, but there's no way to represent these "NOT" types in TypeScript so it isn't likely. It's important that Zod's inferred types accurately reflect what will pass validation. The closest thing that I'd be willing to introduce is an .exclude() method to mirror Exclude.

Then you could do something like z.unknown().exclude(z.string()) and the inferred type would be Exclude<any, string> (which is just unknown again).

@JGJP
Copy link

JGJP commented Apr 22, 2024

@colinhacks I think the .exclude() that you suggest is in line with the proposal, but if the input is typed then it should be generic and operate on that type.

@Kumar06Lav
Copy link

I've submitted a PR to add support for type negation using z.not() and the .not() method in schema validation.

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

No branches or pull requests

5 participants