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

如何阻止Vuetify 3 v-combobox验证失败时添加新项?

解决v-combobox验证不通过仍添加项的问题

要实现验证失败时不将不符合规则的标签添加到状态中,你需要拦截v-combobox的默认添加行为,只允许通过验证的项加入。以下是具体实现步骤:

1. 编写验证规则正则

针对你的需求(禁止以数字开头或全为数字的标签),用这个正则匹配不允许的内容:

const invalidTagRegex = /^(\d+|\d.*)$/

解释:

  • ^\d+:匹配全数字的字符串
  • ^\d.*:匹配以数字开头的任意字符串
    两者组合后,只要匹配上就是不符合规则的标签。

2. 修改子组件MultiselectComponent.vue

接收父组件传递的v-model值,拦截更新事件,在更新前验证新添加的项:

<template>
  <v-combobox 
    multiple 
    chips 
    closable-chips 
    clearable 
    :return-object="false"
    variant="outlined"
    :model-value="localValue"
    @update:model-value="handleModelUpdate"
    :rules="rules"
  />
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  rules: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const localValue = ref([...props.modelValue])

// 同步父组件的modelValue变化
watch(() => props.modelValue, (newVal) => {
  localValue.value = [...newVal]
}, { deep: true })

const handleModelUpdate = (newValues) => {
  // 找出本次新增的项
  const addedItems = newValues.filter(item => !localValue.value.includes(item))
  
  // 过滤掉不符合规则的新增项
  const validAddedItems = addedItems.filter(item => {
    return !/^(\d+|\d.*)$/.test(item)
  })
  
  // 合并旧值与合法新增项
  const finalValues = [...localValue.value, ...validAddedItems]
  
  // 更新本地值并通知父组件
  localValue.value = finalValues
  emit('update:modelValue', finalValues)
}
</script>

3. 调整父组件ParentComponent.vue

传递验证规则,同时保留错误提示功能:

...
<template>
  <MultiSelect
    v-model="form.tags"
    label="Select Tags"
    :items="tags"
    item-title="name"
    item-value="id"
    :rules="tagRules"
  />
</template>

<script setup>
const tagRules = [
  (value) => {
    if (!value) return true
    return !/^(\d+|\d.*)$/.test(value) || '标签不能以数字开头或全为数字'
  }
]
</script>
...

说明

核心逻辑是通过@update:model-value事件拦截默认更新行为,手动过滤不符合规则的新增项,只将合法项同步到v-model中。如果不需要错误提示,可去掉rules相关的传递与绑定,仅保留过滤逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:43:11