Home > Back-end >  Run event with input length value and made a validation
Run event with input length value and made a validation

Time:06-19

I'm new in Vue.js and I see we can run methods over fields, in this case, I want to run an event over my input in order to only accept 5 numbers, so if numbers > 5 remove it

My try:

<input type="number" min="0" @onkeydown="limitText($event)">

Method:

limitText(value: any) {
      console.log('it is working')
    },

But the event does not execute. How can I achieve that? Regards

CodePudding user response:

You can achieve this by using @keyup event. As per my understanding, You want to check the length of the input value on key press and if it exceeds 5 then you are making the field blank. If Yes, here you go :

new Vue({
  el: '#app',
  data: {
    inputValue: null
  },
  methods: {
    limitText() {
      if (this.inputValue.length > 5) {
        this.inputValue = null;
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="number" min="0" v-model="inputValue" @keyup="limitText">
</div>

If You want to check the input value instead of length, then you can little twik the logic. Use if (this.inputValue > 5) { ... } instead of if (this.inputValue.length > 5) { ... }

  • Related