How to build an optional form? #12553
-
I want to build something like this:
And this component will actually render these inputs in combination, like email with password, phone with password and so on. {signInData.supportAuthType === "phone" && (
<FormField
control={form.control}
name="phone"
render={({ field }) => (
...
</FormItem>
)}
/>
)} But in the schema, I haven't find a way to do this clearly. If I use some optional setting, I will easily got typescript errors, which I think this should not the correct way to do this. const FormSchema = z.object({
...(signInData.supportAuthType === "phone" && {
phone: // checks here
}), So in my scenario, if I don't do it optionally in schema, I can't submit because schema thinks there are inputs that are empty and they will not passed the check, and else I haven't find a way to make all of them optionally. Is there any best practices to achieve this? I don't think build multiple forms based on configs is a good idea. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Can you include a CodeSandbox example that explains what you are trying to accomplish? If you only want to validate one of the input options, you can try using a Zod discriminated union. const PhoneSchema = z.object({
type: "phone",
phone: z.string(),
});
const EmailSchema = z.object({
type: "email",
email: z.string().email(),
});
const FormSchema = z.discriminatedUnion("type", [PhoneSchema, EmailSchema]); |
Beta Was this translation helpful? Give feedback.
Can you include a CodeSandbox example that explains what you are trying to accomplish?
If you only want to validate one of the input options, you can try using a Zod discriminated union.