zod icon indicating copy to clipboard operation
zod copied to clipboard

Although `z.string().date()` check fails, yet the callback to `.superRefine()` is executed.

Open aaditmshah-commversion opened this issue 5 months ago • 0 comments

Consider the following schema.

import { z } from "zod";

export const dateRangeSchema = z.object({
    minimum: z.string().date(),
    maximum: z.string().date(),
}).superRefine(({ minimum, maximum }, context) => {
    console.log({ minimum, maximum }); // for debugging

    if (new Date(minimum) > new Date(maximum)) {
        context.addIssue({
            code: z.ZodIssueCode.too_big,
            type: "date",
            maximum,
            inclusive: true,
            path: ["minimum"],
            message: "minimum must not be greater than maximum",
        });

        context.addIssue({
            code: z.ZodIssueCode.too_small,
            type: "date",
            minimum,
            inclusive: true,
            path: ["maximum"],
            message: "maximum must not be lesser than minimum",
        });
    }
});

I expect when minimum or maximum are invalid date strings, then the callback to .superRefine() won't be executed. However, this is not the case. Consider the following example.

console.log(dateRangeSchema.safeParse({ minimum: "1", maximum: "0" }).error.issues);

The above example prints out the following output to the console.

{ minimum: '1', maximum: '0' }
[
  {
    code: 'invalid_string',
    validation: 'date',
    message: 'Invalid date',
    path: [ 'minimum' ]
  },
  {
    code: 'invalid_string',
    validation: 'date',
    message: 'Invalid date',
    path: [ 'maximum' ]
  },
  {
    code: 'too_big',
    type: 'date',
    maximum: '0',
    inclusive: true,
    path: [ 'minimum' ],
    message: 'minimum must not be greater than maximum'
  },
  {
    code: 'too_small',
    type: 'date',
    minimum: '1',
    inclusive: true,
    path: [ 'maximum' ],
    message: 'maximum must not be lesser than minimum'
  }
]

As you can see, although "1" and "0" fail the z.string().date() check, yet the callback to .superRefine() is executed. This is unintuitive behavior. At the very least, it violates the principle of least astonishment. The callback to .superRefine() should only be executed when the input is parsed without any issue.

aaditmshah-commversion avatar Sep 13 '24 09:09 aaditmshah-commversion