Repository navigation
Using zod form validation with radio button group that has no default checked value on first render #3640
Replies: 3 comments
|
Interesting, this is the exact situation I am in right now. |
|
I am facing the same issue, but I thought it could be something like this where we union the field with For example, z.union([
z.enum(["option-0", "option-1", "option-2"].optional(),
z.literal(""),
]) |
|
You can allow With Zod 4: const choices = ["option-0", "option-1", "option-2"] as const;
const selected = z.enum(choices, {
error: "You must select an option",
});
const FormSchema = z.object({
options: selected.or(z.literal("")).pipe(selected),
});
type Input = z.input<typeof FormSchema>;
type Output = z.output<typeof FormSchema>;
const form = useForm<Input, unknown, Output>({
resolver: zodResolver(FormSchema),
defaultValues: { options: "" },
});
// Inside the form:
{choices.map(value => (
<label key={value}>
<input type="radio" value={value} {...form.register("options")} />
{value}
</label>
))}None of those native radio values matches For Zod 3, the same pipeline works; replace the enum options with Verified with Zod 3.25.76 / 4.6.7, React Hook Form 7.65.0, resolvers 5.2.2 and strict TypeScript 5.9.3: empty/invalid input fails, all three choices pass, and The resolver documentation describes the separate input/output generics. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a simple form that I am using
zodto validate. For simplicity let's say the form has exactly one user field for specifying a selection:The above code does not work since
""is not in the set of options specified in theFormSchema.Is there a way to:
All reactions