Vuetify多选v-select必填验证规则失效问题求助
Got it, let's break down why your multi-select required validation isn't working and fix it up.
The Problem
Here's what you're encountering:
- When using
v-selectwithout themultipleprop (single-select mode), the required validation rule works exactly as expected. - When enabling
multiple(multi-select mode), the same rule stops triggering the error message even when no options are selected.
Expected behavior: The required validation should enforce selecting at least one option in multi-select mode.
Actual behavior: No error is shown when no options are selected in multi-select mode.
Why This Happens
The root cause lies in how JavaScript evaluates empty arrays vs. empty single values:
- In single-select mode, your
v-model(roleee) starts asundefinedornull, so!!vcorrectly evaluates tofalsewhen nothing's selected, triggering the error. - In multi-select mode, your
v-model(subsidiariesss) defaults to an empty array[]. In JavaScript,!![]returnstrue(since arrays are objects, and non-null objects are truthy), so your original rulev => !!v || 'Item is required'never triggers the error message.
The Fix
Update your validation rule to check if the value is an array and verify its length is greater than 0. This rule will work seamlessly for both single and multi-select cases:
rules: { select: [v => (Array.isArray(v) ? v.length > 0 : !!v) || 'Item is required'] }
Full Working Code
I also added explicit initial values for your v-model variables (good practice for clarity) and fixed the reset method since your original code references a form ref that doesn't exist:
<div id="app"> <v-app id="inspire"> <v-select :items="role" label="Admin level*" class="mt-3" @focus="resetValidation" item-text="name" item-value="name" v-model="roleee" required :rules="rules.select" ref="singleSelect" ></v-select> <v-select :items="subsidiaries" label="Subsidiary*" class="mt-3" @focus="resetValidation" item-text="name" item-value="name" v-model="subsidiariesss" multiple required :rules="rules.select" :menu-props="{ bottom: true, offsetY: true }" ref="multiSelect" ></v-select> </v-app> </div> <script> new Vue({ el: '#app', data: { role: [{name:'Admin', id:1}, {name: 'SuperAdmin', id:2}], subsidiaries: [ {name: "ASdsad", id:1}, {name: "dsd", id:2}, {name: "34", id:3}, {name: "ASvxcdsad", id:4} ], rules: { select: [v => (Array.isArray(v) ? v.length > 0 : !!v) || 'Item is required'] }, roleee: null, // Initialize single-select value to null subsidiariesss: [] // Initialize multi-select value to empty array }, methods: { resetValidation() { // Reset validation for both selects this.$nextTick(() => { this.$refs.singleSelect?.resetValidation(); this.$refs.multiSelect?.resetValidation(); }); }, } }) </script>
This code will now correctly show the "Item is required" error when no options are selected in either single or multi-select mode.
内容的提问来源于stack exchange,提问作者simpledev

