最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to setup UForm and UFormGroup in NuxtUI such that errors apply for nested dynamic form? - Stack Overflow

matteradmin8PV0评论

I have a form like the following example:

<template>
  <div>
    <h1>Training Form</h1>
  </div>
  <UForm :state="state" :schema="schema" @submit="handleSubmit">
    <UFormGroup label="Name" name="name">
      <UInput v-model="state.name" />
    </UFormGroup>
    <UFormGroup label="Training Week" name="trainingWeek">
      <div v-for="(day, index) in state.trainingWeek" :key="index">
        <UFormGroup label="Day" name="trainingWeek[' + index + '].day">
          <UInput v-model="day.day" />
        </UFormGroup>
        <UFormGroup label="Exercises" name="trainingWeek[' + index + '].exercises">
          <div v-for="(exercise, exerciseIndex) in day.exercises" :key="exerciseIndex">
            <UInput v-model="exercise.exerciseName" />
          </div>
        </UFormGroup>
        <div class="mt-4 flex justify-end">
          <UButton @click="addExercise(index)">Add Exercise</UButton>
        </div>
      </div>
    </UFormGroup>
    <div class="mt-4 flex justify-end">
      <UButton @click="addDay">Add Day</UButton>
      <UButton type="submit">Submit</UButton>
    </div>
  </UForm>
</template>

<script setup lang="ts">
import { z } from "zod";
import type { FormSubmitEvent } from "#ui/types";
const state = reactive({
  name: "",
  trainingWeek: [
    {
      day: "",
      exercises: [
        {
          exerciseName: "",
        },
      ],
    },
  ],
});

const schema = z.object({
  name: z.string().min(1, "Required field"),
  trainingWeek: z.array(
    z.object({
      day: z.string().min(1, "Required field"),
      exercises: z.array(
        z.object({
          exerciseName: z.string().min(1, "Required field"),
        }),
      ),
    }),
  ),
});

type Schema = z.infer<typeof schema>;

const handleSubmit = (event: FormSubmitEvent<Schema>) => {
  console.log(JSON.stringify(event.data, null, 2));
};

const addExercise = (index: number) => {
  state.trainingWeek[index].exercises.push({ exerciseName: "" });
};

const addDay = () => {
  state.trainingWeek.push({ day: "", exercises: [{ exerciseName: "" }] });
};
</script>

I render the form based on state and dynamically add fields.

The form automatically sets up errors for name ( or any first level fields ) but doesn't set up errors for nested ones like day or exerciseName in the above example

What's the proper way to create dynamic forms and avail error setting ?

I'm able to get the following:

profile.vue:68 ZodError: [
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "day"
    ]
  },
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "exercises",
      0,
      "exerciseName"
    ]
  }
]

output by parsing schema

watchEffect(() => {
  try {
    schema.parse(state);
  } catch (error) {
    console.error(error);
  }
});

I have a form like the following example:

<template>
  <div>
    <h1>Training Form</h1>
  </div>
  <UForm :state="state" :schema="schema" @submit="handleSubmit">
    <UFormGroup label="Name" name="name">
      <UInput v-model="state.name" />
    </UFormGroup>
    <UFormGroup label="Training Week" name="trainingWeek">
      <div v-for="(day, index) in state.trainingWeek" :key="index">
        <UFormGroup label="Day" name="trainingWeek[' + index + '].day">
          <UInput v-model="day.day" />
        </UFormGroup>
        <UFormGroup label="Exercises" name="trainingWeek[' + index + '].exercises">
          <div v-for="(exercise, exerciseIndex) in day.exercises" :key="exerciseIndex">
            <UInput v-model="exercise.exerciseName" />
          </div>
        </UFormGroup>
        <div class="mt-4 flex justify-end">
          <UButton @click="addExercise(index)">Add Exercise</UButton>
        </div>
      </div>
    </UFormGroup>
    <div class="mt-4 flex justify-end">
      <UButton @click="addDay">Add Day</UButton>
      <UButton type="submit">Submit</UButton>
    </div>
  </UForm>
</template>

<script setup lang="ts">
import { z } from "zod";
import type { FormSubmitEvent } from "#ui/types";
const state = reactive({
  name: "",
  trainingWeek: [
    {
      day: "",
      exercises: [
        {
          exerciseName: "",
        },
      ],
    },
  ],
});

const schema = z.object({
  name: z.string().min(1, "Required field"),
  trainingWeek: z.array(
    z.object({
      day: z.string().min(1, "Required field"),
      exercises: z.array(
        z.object({
          exerciseName: z.string().min(1, "Required field"),
        }),
      ),
    }),
  ),
});

type Schema = z.infer<typeof schema>;

const handleSubmit = (event: FormSubmitEvent<Schema>) => {
  console.log(JSON.stringify(event.data, null, 2));
};

const addExercise = (index: number) => {
  state.trainingWeek[index].exercises.push({ exerciseName: "" });
};

const addDay = () => {
  state.trainingWeek.push({ day: "", exercises: [{ exerciseName: "" }] });
};
</script>

I render the form based on state and dynamically add fields.

The form automatically sets up errors for name ( or any first level fields ) but doesn't set up errors for nested ones like day or exerciseName in the above example

What's the proper way to create dynamic forms and avail error setting ?

I'm able to get the following:

profile.vue:68 ZodError: [
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "day"
    ]
  },
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "exercises",
      0,
      "exerciseName"
    ]
  }
]

output by parsing schema

watchEffect(() => {
  try {
    schema.parse(state);
  } catch (error) {
    console.error(error);
  }
});
Share Improve this question asked Nov 18, 2024 at 16:52 Adharsh MAdharsh M 3,8624 gold badges19 silver badges28 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I should be using . instead of [ ]

eg:

:name="`trainingWeek.${index}.day`" 

instead of

:name="trainingWeek[' + index + '].day">

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far