zod icon indicating copy to clipboard operation
zod copied to clipboard

"validation" field should be optional on `ZodInvalidStringIssue` type

Open Dan503 opened this issue 1 year ago • 1 comments

This is mainly a concern when using superRefine

z.object({ one: z.string(), two: z.string() })
.superRefine((value, context) => {
    if (!value.one && !value.two) {
        context.addIssue({
            code: ZodIssueCode.invalid_string,
            message: 'Need to enter one or two',
            // I do not care what the format of the string is. I only care that a value exists.
            validation: { includes:'' }
        })
    }
});

The above example demonstrates why validation should be optional.

(Note this is a reduced test case, this one could be converted to a simple .refine() but my real world version cannot)

Dan503 avatar Apr 03 '24 10:04 Dan503

Hm. I think that's a good idea generally but not in your particular case. Since you're trying to enforce an "OR" condition, you should just use ZodIssueCode.invalid_type. By contrast invalid_string is used when a string fails a string-specific validation (too long, too short, failed regex check, etc).

This is all quite nitpicky of course, and I think this is a valid feature request for other use cases where custom string validations are being performed.

colinhacks avatar Apr 04 '24 03:04 colinhacks