shentao / vue-multiselect

Universal select/multiselect/tagging component for Vue.js
https://vue-multiselect.js.org/
MIT License
6.67k stars 989 forks source link

How to make the filed required? #599

Closed akbarkz closed 6 years ago

akbarkz commented 6 years ago

I didn't notice a way to make multiselect component required. It always allows me to submit empty multiselect where I don't select any options at all. I think it's better to include a prop that would control requiredness.

PrimozRome commented 6 years ago

I think it's better to control this with any-kind of form validation library... Additionally take a look at this example. Shows you how to do this validation that you want > https://vue-multiselect.js.org/#sub-custom-configuration

shentao commented 6 years ago

Thanks @PrimozRome!

TheAndroidGuy commented 6 years ago

@shentao when i add the required attribute to the input field in the html via chrome it works perfectly.

Can you somehow make it possible to add that attribute to the input field?

Here is screenshot.

adrianoresende commented 6 years ago

@shentao I recommend (very) to add props required in input. Makes it easy with submit button and more semantics.

andreasvirkus commented 5 years ago

Please consider reopening this/making this toggleable @shentao 🙏

shentao commented 5 years ago

@adrianoresende except when the input is not searchable. And when it’s a multiselect where the value isn’t stored in the input. You need to use JavaScript to validate it.

rationalthinker1 commented 3 years ago

I had to use this method whenever the multiselect is changed.

  updateFieldRequired() {
      this.$nextTick(() => {
        const required = this.required && (this.option == null || (Array.isArray(this.option) && this.option.length == 0) && this.options.length > 0);
        this.$refs.multiselect.$el.querySelector('input').required = required;
      });
    },
asilverstein commented 3 years ago

I had to use this method whenever the multiselect is changed.

  updateFieldRequired() {
      this.$nextTick(() => {
        const required = this.required && (this.option == null || (Array.isArray(this.option) && this.option.length == 0) && this.options.length > 0);
        this.$refs.multiselect.$el.querySelector('input').required = required;
      });
    },

Thanks for this, saved me some time.

mlwade commented 2 years ago

Add this to your v-select component. When a v-select has the 'multiple' attribute, the validation checks an array. An empty array is considered truthy, therefore the validation passes. You need to check the length of v.

:rules="[v => !!v.length] || 'This is a required field!'"

zlatanMkare commented 1 year ago

You can use vee-validate's to validate the Multiselect. Wrap the multiselect in a validation provider

<ValidationProvider v-slot="{ errors }" rules="required">
     <Multiselect></Multiselect>
     <span class="error">{{ errors[0] }}</span>
</ValidationProvider>