only positive integers can be entered
according to the keypress event, monitor the keyboard keyCode code, combined with the numeric regular expression to determine whether the typed keyCode is a number, if it is non-numeric, call the preventDefault event to prevent the default behavior
code so that only 0-9 can be entered, all other characters can not be entered, simple and rude
Vue.directive("enterNumber", {
inserted: function (el) {
el.addEventListener("keypress",function(e){
e = e || window.event;
let charcode = typeof e.charCode == "number" ? e.charCode : e.keyCode;
let re = /\d/;
if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
});
}
});
can only enter positive numbers (including decimals)
this instruction is modified on the above instruction, that is, decimal points are allowed to be entered, but if you simply allow the entry of decimal points, it will result in innumerable decimal points such as 1.1.1.1.1
. All the processing here is that if the decimal point is entered for the first time, it will be released. But the next time you press the decimal point keyCode on the keyboard, the input value will be judged. If there is a decimal point in the value value, preventDefault () will be called to block the event
Vue.directive("enterNumber2", {
inserted: function (el) {
el.addEventListener("keypress",function(e){
e = e || window.event;
let charcode = typeof e.charCode == "number" ? e.charCode : e.keyCode;
let re = /\d/;
if(charcode == 46){
if(el.value.includes(".")){
e.preventDefault();
}
return;
}else if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
});
}
});
there is no problem for these two instructions to type input under the English input method, but it does not take effect under the Chinese input method. Try to improve the solution