You can use the maxlength
property to restrict the length of entered text in an input
field or a textarea
. To allow allow numbers, you will need to create an Array with the allowed keyCodes and check if the event's keycode exists in the Array.
<input type="text" maxlength="14" onkeydown="return isAlpha(event)">
<script>
function isAlpha(e){
e = e||window.event;
var key = e.which||e.keyCode;
var nums = [8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36];
return nums.indexOf(key)!==-1;
}
</script>
However, you can just use <input type="number">
to only allow numeric input. You can use the max
and min
attributes to limit the range of the numbers. maxlength
does not work on a numeric input, but I have added a workaround. You may also want to prevent the e
key (keyCode 69) from being entered because it is valid inside a number.
<input type="number" min="1" max="99999999999999" maxlength="14" oninput="checkNumOfChars(this);" onkeydown="preventE(event)">
<script>
function checkNumOfChars(elem){
if (elem.value.length > elem.maxLength){
elem.value = elem.value.slice(0, elem.maxLength);
}
}
function preventE(event){
if(event.keyCode===69){
event.preventDefault();
}
}
</script>