Vue : Limit characters in text area input, truncate filter?

Viewed 40509

<textarea name="" id="" cols="30" rows="10" v-model="$store.state.user.giftMessage | truncate 150"></textarea> I tried creating a custom filter :

filters: {
    truncate(text, stop, clamp) {
        return text.slice(0, stop) + (stop < text.length ? clamp || '...' : '')
    }
}

but that didn't broke the build when I put it on the v-model for the input...

Any advice?

8 Answers

Sorry to break in. Was looking for a solution. Looked at all of them. For me they look too complicated. I'm always looking for symplicity. Therefor I like the answer of @Даниил Пронин. But it has the by @J. Rambo noted potential problem.

To stay as close as possible to the native html textelement. The solution I came up with is:

Vue Template

<textarea v-model="value" @input="assertMaxChars()">

JavaScript

let app = new Vue({
  el: '#app',
  data: {
    value: 'Vue is working!',
    maxLengthInCars: 25
  },

  methods: {
    assertMaxChars: function () {
        if (this.value.length >= this.maxLengthInCars) {
            this.value = this.value.substring(0,this.maxLengthInCars);
        }
    }
  }
})

Here is a REPL link: https://repl.it/@tsboh/LimitedCharsInTextarea

The upside I see is:

  • the element is as close as possible to the native element
  • simple code
  • textarea keeps focus
  • delete still works
  • works with pasting text as well

Anyway happy coding

While I agree with the selected answer. You can also easily prevent the length using a keydown event handler.

Vue Template

<input type="text" @keydown="limit( $event, 'myModel', 3)" v-model="myModel" />

JavaScript

export default {
    name: 'SomeComponent',

    data () {
        return {
            myModel: ''
        };
    },

    methods: {

        limit( event, dataProp, limit ) {
            if ( this[dataProp].length >= limit ) {
               event.preventDefault();
            }
        }
    }
}

Doing this way, you can also use regular expression to event prevent the type of keys accepted. For instance, if you only wanted to accept numeric values you can do the following.

methods: {
   numeric( event, dataProp, limit ) {
       if ( !/[0-9]/.test( event.key ) ) {
           event.preventDefault();
       }
   }
} 

I have improved on @J Ws answer. The resulting code does not have to define how to react on which keypress, which is why it can be used with any character in contrast to the accepted answer. It only cares about the string-length of the result. It also can handle Copy-Paste-actions and cuts overlong pastes to size:

Vue.component("limitedTextarea", {
    props: {
      value: {
        type: String,
        default: ""
      },
      max: {
        type: Number,
        default: 25
      }
    },
    computed: {
      internalValue: {
        get: function () {
          return this.value;
        },
        set: function (aModifiedValue) {
          this.$emit("input", aModifiedValue.substring(0, this.max));
        }
      }
    },
    template: '<textarea v-model="internalValue" @keydown="$forceUpdate()" @paste="$forceUpdate()"></textarea>'
});

The magic lies in the @keydown and @paste-events, which force an update. As the value is already cut to size correctly, it assures that the internalValue is acting accordingly.

If you also want to protect the value from unchecked script-changes, you can add the following watcher:

watch: {
  value: function(aOldValue){
    if(this.value.length > this.max){
      this.$emit("input", this.value.substring(0, this.max));
    }
  }
}

I just found a problem with this easy solution: If you set the cursor somewhere in the middle and type, transgressing the maximum, the last character is removed and the cursor set to the end of the text. So there is still some room for improvement...

My custom directive version. Simple to use.

<textarea v-model="input.textarea" v-max-length="10"></textarea>


Vue.directive('maxlength',{
    bind: function(el, binding, vnode) {
        el.dataset.maxLength = Number(binding.value);
        var handler = function(e) {
            if (e.target.value.length > el.dataset.maxLength) {
                e.target.value = e.target.value.substring(0, el.dataset.maxLength);
                var event = new Event('input', {
                    'bubbles': true,
                    'cancelable': true
                });
                this.dispatchEvent(event);
                return;
            }
        };
        el.addEventListener('input', handler);
    },
    update: function(el, binding, vnode) {
        el.dataset.maxLength = Number(binding.value);
    }
})
  1. Event() has browser compatibility issue.
  2. Unfortunately for me, keydown approach seems not working good with CJK.
  3. there can be side effects since this method fires input event double time.

Best way is to use watch to string length and set old value if string is longer than you want:

watch: {
    'inputModel': function(val, oldVal) {
        if (val.length > 250) {
            this.inputModel = oldVal
        }
    },
},

Simply use maxlength attribute like this:

<textarea v-model="value" maxlength="50" />
Related