Zod overrides react-hook-form validation

I have the following form scheme. When I specify rules={{required: true}} on the field it doesn't work because of zod validation scheme.
const trendyolFormScheme = z.object({
brand: z.string().optional(),
attributes: z.array(
z
.object({
attributeId: z.number(),
customAttributeValue: z.string().optional(),
attributeValueId: z.number().optional(),
})
.optional(),
),
});
const trendyolFormScheme = z.object({
brand: z.string().optional(),
attributes: z.array(
z
.object({
attributeId: z.number(),
customAttributeValue: z.string().optional(),
attributeValueId: z.number().optional(),
})
.optional(),
),
});
I want to be able to override Zod or being able to make field required based on api response (later on).
Solution:
And as you mentioned you can make it required based on api response, you can use a discriminated union to make things required depending on some data from the api https://zod.dev/?id=discriminated-unions
Jump to solution
4 Replies
Kseikyo
Kseikyo15mo ago
Zod is your validation, so if you want things to be required, they have to be done on the schema. Or at least you can create a required version of that schema by calling .required();
const requiredTrendyolFormScheme = trendyolFormScheme.required();
const requiredTrendyolFormScheme = trendyolFormScheme.required();
https://zod.dev/?id=required
Solution
Kseikyo
Kseikyo15mo ago
And as you mentioned you can make it required based on api response, you can use a discriminated union to make things required depending on some data from the api https://zod.dev/?id=discriminated-unions
theart4290
theart429015mo ago
Sounds like you want to run some manual validations first and then parse it with a stricter zod schema. Is that the case? Alternatively you could make it required initially and then handle parsing errors however you want.
Omar-7ioo
Omar-7iooOP15mo ago
I used discriminatedUnion and refined. It wasn't the cleanest thing but it does the job. Thanks 🙏. Thanks for your suggestion
Want results from more Discord servers?
Add your server