[Vuejs]-Vue.js input field still accepts character input

0đź‘Ť

Problem 1: (if you’re using Keen UI) Keen UI textbox element doesn’t support keypress event

https://josephuspaye.github.io/Keen-UI/#/ui-textbox

enter image description here

Problem 2: the event in isNumber(event) is unnecessary. Simply isNumber will do. (in scenario where you need to pass the event, the correct syntax is isNumber($event))

suggestion to you :

change v-on:keypress="isNumber(event)" to v-on:keydown="isNumber"


Update: improve isNumber Function. Add 1 more validation to check if the key is number using isNaN. See isNaN(evt.key) below

methods: {
    isNumber: function(evt) {
        console.log("Im in");
        evt = evt ? evt : window.event;
        var charCode = evt.which ? evt.which : evt.keyCode;
        if (
            charCode > 31 &&
            (charCode < 48 || charCode > 57) &&
            charCode !== 46
        ) {
            evt.preventDefault();
        } else if(isNaN(evt.key)){
            evt.preventDefault();
        } else {
            return true;
        }
    }
}

0đź‘Ť

Have you tried adding type=”number”?

so:

<div class="flexItem">
     <ui-textbox label="test" v-model="prospect.monthly_cost"
         name="testmonth"
         v-validate="`${vRequired}|decimal`"
         v-on:keypress="isNumber(event)"
         :invalid="errors.has('monthly_cost')"
         :error="errors.first('monthly_cost')"
         type="number"
     ></ui-textbox>
</div>

Leave a comment