javascriptvue.jsvue-material

Limit string length in vue material chips


I'm using Vue Material Chips component to collect some string arrays, and I have to limit the length of each string (let's say, 30 characters).

They have the md-limit prop, it limits the number of strings I can have in my array but not the number of chars I can have on each string.

I do believe I'll have to build a custom validation before adding each string to the array (I've tried to use v-validate but it doesn't seem to have any effect on the chips component).

If anybody had a suggestion how could I achieve it, it would be very appreciated! Tnx


Solution

  • So if I got this right

    1. You have an array with your chips inside (ex: this.fruits = ['Banana','Apple','Pineapple','SomeOtherFruitWithMoreThan30Chars'])
    2. When you hit enter, the v-model variable gets updated and pushes your input into that array

    What I would do:

    1. Make a deep watch (maybe normal works fine)
    watch: {
      fruits:{
        // newVal is the new value of the array
        handler: function(newVal) {
    
          //checks if the last element of the array has more than 30 chars
          if(newVal[(newVal.length - 1)].length > 30){
            //remove the last element of the array
            this.fruits.pop()
          }
        },
        deep: true
      }
    }
    
    1. Try to use the formatter function of the component as a validation check md-format and return null if more than 30 chars