I have a simple password text input, and I want to show multiple errors below the input, but I have noticed that zod only returns one error at a time even if I use superRefine
here are some codes that I did (I have tested more but I don't have them for copying)
Notice that I am not adding any validation on purpose because I want to see an array of errors
password: z.string().superRefine((val, ctx) => {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `test1.`,
});
debugger;
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `test2.`,
});
}),
this is what I started with before I realized this won't return me a list of errors
password: z
.string()
.min(8, { message: 'min' })
.regex(/^[A-Z]*$/, { message: 'uppercase' })
.regex(/\d/, { message: 'number' }),
fyi I am using react
, react-hook-forms
and zod
I am expecting zod to return me a list of errors of a simple password text input
It does return a list of errors:
import { z } from 'zod';
const ExampleSchema = z.object({
password: z
.string()
.min(8, { message: 'min' })
.regex(/^[A-Z]*$/, { message: 'uppercase' })
.regex(/\d/, { message: 'number' }),
});
const testData = { password: 'aaaaa' };
try {
ExampleSchema.parse(testData);
} catch (e) {
console.log(e.issues);
}
This outputs
[
{
"code": "too_small",
"minimum": 8,
"type": "string",
"inclusive": true,
"exact": false,
"message": "min",
"path": [
"password"
]
},
{
"validation": "regex",
"code": "invalid_string",
"message": "uppercase",
"path": [
"password"
]
},
{
"validation": "regex",
"code": "invalid_string",
"message": "number",
"path": [
"password"
]
}
]
The error object contains an issues
key which I think is what you want.