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

date validation optional not working #1671

Closed
rayanazzam1991 opened this issue Dec 12, 2022 · 2 comments
Closed

date validation optional not working #1671

rayanazzam1991 opened this issue Dec 12, 2022 · 2 comments

Comments

@rayanazzam1991
Copy link

Hello i am trying to validate date but i want it optional that means if the user enter a date then validate it but if he/she left it with no value i don't want to validate it.
birth_date: zod.date().optional(),
that's not worked for me

@igalklebanov
Copy link
Contributor

Hey 👋

What errors are you getting?

@colinhacks
Copy link
Owner

Can't replicate, this is working for me.

const schema = z.object({
  birth_date: z.date().optional(),
});

schema.parse({});

My guess is that the form is returning a default value of "" when no input is entered into the form. There's a few ways to handle this:

const schema = z.object({
  birth_date: z.date().optional().catch(undefined),  // any error will cause `undefined` to be returned
  birth_date: z.preprocess(val => val === "" ? undefined : val, z.date().optional()) // convert empty string to undefined with preprocess
})

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

3 participants