3

I need to create a validation that prevent the user from inputting numeric inputs on a textbox. I found some solution using a native javascript but it is not working on my side.

On my text box I have this trigger

v-on:keyup="preventNumericInput($event)"> 

And on my Vue I created a function on my class

preventNumericInput($event) {
    console.log($event.keyCode); //will display the keyCode value
    console.log($event.key); //will show the key value

    var keyCode = ($event.keyCode ? $event.keyCode : $event.which);
    if (keyCode > 47 && keyCode < 58) {
        $event.preventDefault();
    }
}

Can you help me with this?

Jerielle
  • 7,144
  • 29
  • 98
  • 164

3 Answers3

5

As mentioned in my comment, keyup will be firing too late to prevent the value being entered into the input field. For example, think about holding a key down to enter the same value repeatedly; there is no key up.

Instead, usekeydown or keypress

<input @keypress="preventNumericInput">

Demo ~ http://jsfiddle.net/wadt08jm/1/

Yeonho
  • 3,629
  • 4
  • 39
  • 61
Phil
  • 157,677
  • 23
  • 242
  • 245
0
  • Input must be type number, otherwise isNaN won't work

       <input type="number" :value="price" step="0.1" min="0" @input="onInput($event)" >
    
  • into input replace ',' by '.'

  • test if not number

  • if not number replace observable price by element.value

  data () {
    return { price: 0 }
  },
  methods: {
    onInput (e: Event) {
      const element = e.target as HTMLInputElement
      const value = parseFloat(element.value === '' ? '0' : element.value.replace(',', '.'))
      if (isNaN(value)) {
        element.value = this.price.toString()
      } else {
        this.price = value
      }
    }
  }
renaud H
  • 94
  • 6
0

In Vue 3, you can turn off the scroll to change when input type is number feature by modifying the input element's behavior using a directive. Here is the directive:

beforeMount(el, binding, vnode, prevVnode) {
  el.addEventListener('wheel', (event) => {
    if (el.type === 'nunmber') {
        el.blur()
        event.preventDefault()
      }
    },
    { passive: false }
)},
unmounted(el, binding, vnode, prevVnode) {
 document.body.removeEventListener('wheel', (event) => {
   el.blur()
   event.preventDefault()
 })
}
Alper Guven
  • 81
  • 1
  • 5