Replies: 1 comment
-
It's a little verbose, but this works and keeps the type inference intact const subGroupSchema = z.object({
id: z.string(),
name: translationSchema,
});
const groupBase = z.object(
{
id: z.string(),
name: translationSchema,
},
{
errorMap: (issue, ctx) => ({
message: isNil(ctx.data)
? "core:form.validation.required"
: ctx.defaultError,
}),
}
);
const groupWithSubgroupsSchema = groupBase.merge(
z.object({
subgroups: z.array(subGroupSchema),
})
);
const groupWithoutSubgroupsSchema = groupBase.merge(
z.object({
subgroups: z.null(), // you could also use z.array(z.never()), z.undefined() or simply reuse the base schema for this variant
})
);
const schemaBase = z.object({
skill: skillSchema,
level: z.number().min(1).max(5),
});
export const schema = z.union([
schemaBase.merge(
z.object({
group: groupWithSubgroupsSchema,
subGroup: subGroupSchema,
})
),
schemaBase.merge(
z.object({
group: groupWithoutSubgroupsSchema,
subGroup: z.null(), //Once again, use whatever fits here
})
),
]); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have 2 select fields, the first field lets the user select a group and the second one a subgroup for that selected group.
The validation logic is that it is not guaranteed that a group will have subgroups. So if the user selects a group which won't contain any subgroups there shouldn't be any validation error. If on the other hand the user selects a group which has subgroups the validation rules should change that it is required to select a subgroup.
So what i need is a way to add the required rule to the
subGroupSchema
depending on the value of thegroupSchema
. Here is my schema:I tried setting an
errorMap
on theschema
object but without any luck as also need to place the error message on thesubGroupSchema
object.Is this use case possible while using zod? Thx in advance for any tipp or help!!
Beta Was this translation helpful? Give feedback.
All reactions