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

Vue Vuelidate数组对象选择限制问题:最多选3个禁止提交表单

Vue Vuelidate实现复选框最多选3个限制

步骤1:添加数组长度验证规则

在组件的validations配置中,针对存储选中项的数组(比如user.positions)添加长度限制,要求最大长度为3:

import { maxLength } from 'vuelidate/lib/validators'

export default {
  // ...其他组件配置
  validations: {
    user: {
      positions: {
        maxLength: maxLength(3)
      }
    }
  },
  // ...
}

步骤2:优化复选框点击逻辑(可选)

为了提升用户体验,当已选数量达到3个时,直接阻止添加新选项:

valueSelected(value, index) {
  // 处理mySelectedValue数组
  const i = this.mySelectedValue.indexOf(value)
  if (i === -1) {
    // 已选数量未达3个才允许添加
    if (this.mySelectedValue.length < 3) {
      this.mySelectedValue.push(value)
    }
  } else {
    this.mySelectedValue.splice(i, 1)
  }

  // 处理user.positions数组
  const findIndex = this.user.positions.findIndex(v => v.position === value.position)
  if (findIndex === -1) {
    if (this.user.positions.length < 3) {
      this.user.positions.push(value)
    }
  } else {
    this.user.positions.splice(findIndex, 1)
  }
}

步骤3:根据验证状态禁用提交按钮

在模板中通过Vuelidate的$v对象判断验证状态,禁用不符合要求的提交按钮:

<button 
  type="submit" 
  :disabled="$v.user.positions.$invalid"
>
  提交
</button>

可选:显示错误提示

如果需要给用户明确的反馈,可以在模板中添加错误提示:

<span v-if="$v.user.positions.$error">最多只能选择3个选项</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:55:17