I am trying to combine Zod and Validator.js to validate form data. I want to allow empty strings ""
for optional fields. I think this snippet should work but it does NOT and I cannot figure it out:
const alpha = (maxChar: number = 1) =>
z
.string()
.toUpperCase()
.max(maxChar)
.refine((value) =>
validator.isAlpha(value.replaceAll(" ", ""), "en-US", { ignore: "" })
)
The issue is in your use of the .refine
property. This property is checking the condition validator.isAlpha(value)
, and that is returning false for empty strings. You can enable empty strings with this simple adjustment:
const alpha = (maxChar: number = 1) =>
z
.string()
.toUpperCase()
.max(maxChar)
.refine((value) =>
validator.isAlpha(value) || value.length === 0
); // ^^^^^^ here!