Is it possible to restrict the input of certain characters in HTML5/JavaScript? For example could I have a input textbox on the screen and if the user tries to type a letter it wouldn't show up in the box because I've restricted it to only numbers?
I know you can use pattern which will check on submit, but I want the "bad" characters to just never be entered at all.
Use html5 pattern attribute for inputs:
<input type="text" pattern="\d*" title="Only digits" />
OR
Use html5 number type for input :
<input type="number" />
The input textbox
<input type="text" onKeyDown="myFunction()" value="" />
JavaScript
function myFunction() {
var e = event || window.event; // get event object
var key = e.keyCode || e.which; // get key cross-browser
if (key < 48 || key > 57) { //if it is not a number ascii code
//Prevent default action, which is inserting character
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
}
To slightly improve off of jonhopkins excellent answer, I added backspace and delete key acceptance like so:
function inputValidate(){
var e = event || window.event;
var key = e.keyCode || e.which;
if (((key>=48)&&(key<=57))||(key==8)||(key == 46)) { //allow backspace //and delete
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
}
}
For Restricting Characters symbols like '-' and ','
<input type="text" pattern="[^-,]+">
for restricting numbers
<input type="text" pattern="[^0-9]+">
for restricting alphabets
<input type="text" pattern="[^a-zA-Z]+">
//improved wbt11a function
function numberFieldStrictInput(allowcomma, allownegative) {
var e = event || window.event; // get event object
var key = e.keyCode ||`enter code here` e.which; // get key cross-browser
if(key==8 || key==46 || key == 9 || key==17 || key==91 || key==18 ||
key==116 || key==89 || key==67 || key==88 || key==35 || key==36) //back, delete tab, ctrl, win, alt, f5, paste, copy, cut, home, end
return true;
if(key == 109 && allownegative)
return true;
if(key == 190 && allowcomma)
return true;
if(key>=37 && key<=40) //arrows
return true;
if(key>=48 && key<=57) // top key
return true;
if(key>=96 && key<=105) //num key
return true;
console.log('Not allowed key pressed '+key);
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
//on input put onKeyDown="numberFieldStrictInput(1,0)"
What about this (it supports special keys, like copy, paste, F5 automatically)?
function filterNumericInput() {
var e = event || window.event; // get event object
if (e.defaultPrevented) {
return;
}
const key = e.key || e.code;
if ((e.key.length <= 1) && (!(e.metaKey || e.ctrlKey || e.altKey))) {
if (!((key >= '0' && key <= '9') || (key === '.') || (key === ',') || (key === '-') || (key === ' '))) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}