Allowing empty strings in Validator.js

171 Views Asked by At

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: "" })
    )
1

There are 1 best solutions below

0
On BEST ANSWER

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!