I have the following schema in Zod that requires a valid string input. However, I'm not sure the validation is actually kicking in? Just wondering what I'm doing wrong...
const nameSchema = z.string({
required_error: "Name is required",
invalid_type_error: "Name must be a string",
});
console.log(nameSchema.safeParse("")); //Return the following object
{
"success": true,
"data": ""
}
Empty string is also a string, that's why you are getting success. You have to refine the empty string also to get error response for empty string as below.
const nameSchema = z.string({
required_error: "Name is required",
invalid_type_error: "Name must be a string",
}).refine(data => data.trim() !== "", {
message: "Name cannot be an empty string",
});
console.log(nameSchema.safeParse(""));