Jerielle
Jerielle

Reputation: 7520

How can I prevent numeric inputs using VueJS

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?

Upvotes: 3

Views: 8635

Answers (3)

Alper Guven
Alper Guven

Reputation: 81

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()
 })
}

Upvotes: 0

reno184
reno184

Reputation: 114

  • 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
      }
    }
  }

Upvotes: 0

Phil
Phil

Reputation: 164881

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/

Upvotes: 5

Related Questions