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?

4
  • 1
    Try this: stackoverflow.com/questions/15728261/… Commented Jun 13, 2018 at 1:42
  • You should really be watching the input and reacting to numeric input. Alternatively you could use oninput Commented Jun 13, 2018 at 2:17
  • 1
    keyup might be too late an event to catch. Try keydown or keypress Commented Jun 13, 2018 at 2:18
  • Why don't use the vee-validate ? Commented Jun 13, 2018 at 10:53

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.