Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Zod validation does not seem to trigger for required input

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


>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(""));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading