colinhacks / zod

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

New Feature - Negative Regex #1156

Closed garyham closed 2 years ago

garyham commented 2 years ago

Hi, first of all, really appreciate all the effort on this fantastic library.

I'd like to suggest what I think is a minor improvement...a negative regex test.

Rationale: It can be quite complex to write the inverse of a regex (negative look ahead etc) and would be much simpler to have the ability to negate the result of the match.

Suggestion: Rather than change the current API, I would suggest negex( regex, message) but entirely up to you.

Apologies if there is another idomatic way of achieving the same outcome.

Background: I'm using tiptap as a Wysiwyg editor. When it's input is empty, rather than "", it returns "<p></>". I want to error if the regex does not match /^<p><\/>$/, rather than if it does. Currently I preprocess the input to coerce "<p></>" to "".

scotttrinh commented 2 years ago

Hmm, interesting! I think maybe there is a general "negation" use case here, just not sure what the API for such a feature would be. Maybe something like z.string().except(z.string().regex(...)) where it will allow any type that fails to parse with the specified schema? Definitely a little awkward so worth taking some time to imagine the right design here.

garyham commented 2 years ago

I did think about the general negation case but for me the complexity outweighed any benefit outside of regex. With strings and numbers it's relatively easy to construct the inverse, and for specific cases like uuid() or email(), it's difficult to conceive why the inverse would be useful (e.g. the message would read "enter something that is not an email?")

my 2 cents.

scotttrinh commented 2 years ago

Here are a few use cases I can think of:

Not super common, but seems like we'd need to solve the general case to make the specific one (basically a reverse-refine like call), so might as well enable it.

colinhacks commented 2 years ago

I'd suggest calling this method .not to be in closer agreement with .and and .or.

Though I'm down to include .negex as well - cool name :)

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.