Skip to content
Advertisement

Zod Schema: How to make a field optional OR have a minimum string contraint?

I have a field where I want the value to either be optional OR have the field have a minimum length of 4.

I’ve tried the following:

JavaScript

This passes if I used a value like: "good", but if I’ve got an empty value then it fails.

How do I correctly implement a constraint using zod schemas to make an optional value with a minimum constraint if the value is not empty?

Is it possible to do this without using regex or a regex solution the only way?

Advertisement

Answer

In your case, you consider "" to be the same as undefined (i.e.: when the string is empty, it’s like there’s no string at all).

It’s implementable in Zod this way:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement