Unable to display Zod error for checkbox #596
-
I've made a checkbox field that allows multiple selections. I defined an array schema using Zod. While it correctly triggers validation errors as expected, the error message does not display. Is there a good way to fix this? Here's the relevant code: const favoriteFruits = ["apple", "orange", "banana"] as const;
const schema = z.object({
// Intentionally leaving out 'orange' to trigger a validation error
favoriteFruit: z.enum(["apple", "banana"]).array(),
});
export function Form() {
const [lastResult, action] = useFormState(submitAction, undefined);
const [form, fields] = useForm({
lastResult,
onValidate({ formData }) {
console.log(parseWithZod(formData, { schema: schema }));
return parseWithZod(formData, { schema: schema });
},
shouldValidate: "onInput",
});
return (
<form action={action} {...getFormProps(form)}>
{favoriteFruits.map((fruit) => (
<div key={fruit}>
<input
id={fruit}
type="checkbox"
name={fields.favoriteFruit.name}
value={fruit}
/>
<label htmlFor={fruit}>{fruit}</label>
</div>
))}
<div>{fields.favoriteFruit.errors}</div>
</form>
);
} Also, could the issue be that the return from |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Conform map each field errors simply by the name. In your case, the name of the favoriteFruits field is To fix it, please use Object.entries(fields.favoriteFruit.allErrors).flatMap(([, messages]) => messages) |
Beta Was this translation helpful? Give feedback.
-
@edmundhung Thank you for your advice. However, enum error messages are only displayed once you submit. Is this the specification? step
2024-04-25.8.44.39.mov |
Beta Was this translation helpful? Give feedback.
Conform map each field errors simply by the name. In your case, the name of the favoriteFruits field is
favoriteFruit
instead offavoriteFruit[0]
which result infields.favoriteFruit.errors
being undefined. Similarily, this is why it works properly if you are building a list of fields in which the field names will befavoriteFruit[0]
,favoriteFruit[1]
and so on.To fix it, please use
fields.favoriteFruit.allErrors
instead. This gives you an object that includes all errors underfavoriteFruit
with key being the name of the corresponding errors. If you don't care about the name, you can make it an array like this: