You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 TypeScript中用Zod验证Multiselect选值仍报错如何解决?

解决Multiselect选值后验证错误提示不消失的问题

问题根源

  1. Zod Schema 写法错误:当前z.string().array()的逻辑是将单个字符串拆分为字符数组,而非定义“字符串数组”类型,导致验证逻辑不符合实际需求。
  2. 验证状态未实时更新:若未正确绑定响应式表单值或触发验证事件,VeeValidate无法感知Multiselect的选值变化,错误提示不会自动消失。

解决方案

1. 修正Zod验证规则

将数组类型的验证写法调整为正确格式:

const zodSchema = z.object({
    unit_type_id: z.array(z.string()).nonempty({
      message: "Please select unit type",
    }),
})

2. 绑定正确的响应式表单值

如果使用VeeValidate的useForm,请将Multiselect的v-model绑定到useForm返回的响应式values对象,而非自定义的initialValues,VeeValidate会自动监听值变化并重新验证:

<script setup>
import { useForm } from 'vee-validate';
import * as z from 'zod';

const zodSchema = z.object({
    unit_type_id: z.array(z.string()).nonempty({
      message: "Please select unit type",
    }),
});

const { values, handleSubmit } = useForm({
  validationSchema: zodSchema,
  initialValues: { unit_type_id: [] }
});

const onSubmit = handleSubmit((data) => {
  // 处理表单提交逻辑
});
</script>

<template>
  <VField id="unit_type_id" v-slot="{ field }">
    <VLabel>Unit Type {{ values.unit_type_id }}</VLabel>
    <VControl>
      <Multiselect
        ref="multiselect"
        v-model="values.unit_type_id"
        mode="tags"
        :searchable="true"
        :create-tag="false"
        :close-on-select="false"
        :options="apartmentUnitTypes"
        placeholder="Select Unit Type"
        :attrs="{ field }"
      ></Multiselect>
      <p v-if="field?.errorMessage" class="help has-text-danger">
        {{ field.errorMessage }}
      </p>
    </VControl>
  </VField>
</template>

3. 手动触发字段验证(备选方案)

如果必须使用自定义的initialValues,可以在Multiselect的input事件中手动触发字段验证:

<script setup>
import { useForm } from 'vee-validate';
import * as z from 'zod';

const initialValues = { unit_type_id: [] };
const zodSchema = z.object({
    unit_type_id: z.array(z.string()).nonempty({
      message: "Please select unit type",
    }),
});

const { validateField } = useForm({
  validationSchema: zodSchema,
  initialValues
});

const handleUnitTypeChange = () => {
  validateField('unit_type_id');
};
</script>

<template>
  <VField id="unit_type_id" v-slot="{ field }">
    <VLabel>Unit Type {{ initialValues.unit_type_id }}</VLabel>
    <VControl>
      <Multiselect
        ref="multiselect"
        v-model="initialValues.unit_type_id"
        mode="tags"
        :searchable="true"
        :create-tag="false"
        :close-on-select="false"
        :options="apartmentUnitTypes"
        placeholder="Select Unit Type"
        :attrs="{ field }"
        @input="handleUnitTypeChange"
      ></Multiselect>
      <p v-if="field?.errorMessage" class="help has-text-danger">
        {{ field.errorMessage }}
      </p>
    </VControl>
  </VField>
</template>

内容的提问来源于stack exchange,提问作者Ruhul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:53:25