Seeking to implement validation for a form featuring checkbox selections with corresponding number inputs. When a user selects a profession checkbox, they must enter the number of years of experience they have in the input next to it. The array structure is as follows (default experience set to 1):
const fieldsOfEng = [
{
id: "ELECTRICAL",
name: "Electrical",
experience: 1,
},
{
id: "MECHANICAL",
name: "Mechanical",
experience: 1,
}
]
If verifying user selection against professions array was the sole focus, the schema would resemble:
export const userInfoSchema = z.object({
professions: z
.string()
.array()
.refine((val) => val.some(profession =>
fieldsOfEng
.map((field) => field.name)
.includes(profession))
})
Handling the input registration through react-hook-form:
{fieldsOfEng.map((field) => {
return (
<input
{...register("professions")}
value={field.name}
type="checkbox"
/>
)}
--------------------WHAT I WANT:
Integration of an 'experience' field into the schema for comprehensive validation. A tentative schema structure could be (not accurate yet):
professions: z
.array(
z.object({
name: z.string(),
experience: z.number(),
})
)
.refine(({name}) =>
name.some(({ profession }) =>
fieldsOfEng.map((field) => field.name).includes(profession)
)
)
.refine(({ experience }) => {
experience.some((exp) => exp > 1);
}),
Form layout adjustment considering the schema update:
{fieldsOfEng.map((field) => {
return (
<input
{...register("professions.name")}
value={field.name}
type="checkbox"
/>
<input
{...register("professions.experience")}
value={field.experience}
type="number"
/>
)}
Although form tweaking is possible, the primary focus lies on refining the schema.