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
x
4
1
export const SocialsSchema = z.object({
2
myField: z.optional(z.string().min(4, "Please enter a valid value")),
3
});
4
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
1
21
21
1
import { z } from "zod";
2
import { strict as assert } from "node:assert";
3
4
// `myString` is a string that can be either optional (undefined or missing),
5
// empty, or min 4
6
const myString = z
7
.union([z.string().length(0), z.string().min(4)])
8
.optional()
9
.transform(e => e === "" ? undefined : e);
10
11
const schema = z.object({ test: myString });
12
13
assert( schema.parse({}).test === undefined ); // missing string
14
assert( schema.parse({ test: undefined }).test === undefined ); // string is undefined
15
assert( schema.parse({ test: "" }).test === undefined ); // string is empty
16
assert( schema.parse({ test: "1234" }).test === "1234" ); // string is min 4
17
18
// these successfully fail
19
assert( schema.safeParse({ test: "123" }).success !== true );
20
assert( schema.safeParse({ test: 3.14 }).success !== true );
21