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

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

Open
aaditmshah-commversion opened this issue Sep 13, 2024 · 0 comments

Comments

@aaditmshah-commversion
Copy link

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.

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

No branches or pull requests

1 participant