colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.92k stars 1.18k forks source link

IP Validation + optional is behaving unexpectedly #3649

Open ireznik opened 3 months ago

ireznik commented 3 months ago

Hello,

I've encountered an issue a couple of days ago and did not find any related topics or issues to that. Maybe my assumption is wrong but I've created a simple example to show what is currently not working as (I) intended it will do:

Sandbox

It is possible to chain ip() with optional() - however the validation will fail for an empty string. I've also checked the docs on any exceptions for the usage of optional() but did not find any limitations to that.

Is this a bug or expected behaviour and if so, how can others be made aware of this behaviour?

AimalKhanOfficial commented 3 months ago

Hmm, i couldn't reproduce this. i get a successful feedback for both - here's a screenshot. I've also tried this with version ^3.23.8 and it works as expected:

image
ireznik commented 3 months ago

Did you try my sandbox example? There you can see that is does not work like in your example and I wonder why

Here is the content of my example

import { z } from "zod";

const ipSchema = z.string().ip();
const brokenIpSchemaWithOptional = ipSchema.optional();
console.log(
  "ip schema validation broken: ",
  brokenIpSchemaWithOptional.safeParse("")
);

const workingIpSchema = z.union([ipSchema, z.string().optional()]);
console.log("ip schema validation working: ", workingIpSchema.safeParse(""));