How can I prevent numeric inputs using VueJS

£可爱£侵袭症+ 提交于 2021-01-28 02:08:30

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/50828016/how-can-i-prevent-numeric-inputs-using-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!