.refine() has a when parameter that allows running a refinement even when the base schema validation fails: #4838
However, .superRefine is missing this parameter.
Example
const baseSchema = z.object({
foo: z.number(),
bar: z.number(),
});
const schema = baseSchema.superRefine(
(data, ctx) => {
if (data.foo > 10) {
ctx.addIssue({
code: "custom",
message: "foo must be less than 10",
});
}
},
{
when: ({ value }) =>
baseSchema.pick({ foo: true }).safeParse(value).success,
},
);
const result = schema.safeParse({
foo: 11,
});
//
In the above example, result.error.issues will only contain one error: "Invalid input: expected number, received undefined" and not the error from .superRefine
The above example could be replaced with .refine since it only adds one issue, but for more complex use cases where .superRefine is needed, having .when would be useful.
This is a widely requested feature, see for example:
#479 (comment)
.refine()has awhenparameter that allows running a refinement even when the base schema validation fails: #4838However,
.superRefineis missing this parameter.Example
In the above example,
result.error.issueswill only contain one error: "Invalid input: expected number, received undefined" and not the error from.superRefineThe above example could be replaced with
.refinesince it only adds one issue, but for more complex use cases where.superRefineis needed, having.whenwould be useful.This is a widely requested feature, see for example:
#479 (comment)