1

The below Javascript function restricts Alphabets from input textbox but unfortunately, it doesn't restrict the following symbols # $ % & ( . which I need to restrict them too.

Also, Can I restrict the input to be 14 digits only not less or more?

function restrictAlphabets(e){
    var x=e.which||e.keycode;
    if((x>=48 && x<=57) || x==8 || (x>=35 && x<=40)|| x==46)
        return true;
    else
        return false;
}
StudioTime
  • 22,603
  • 38
  • 120
  • 207
Ahmad
  • 11
  • 1
  • Possible duplicate of [How to force input to only allow Alpha Letters?](https://stackoverflow.com/questions/19508183/how-to-force-input-to-only-allow-alpha-letters) – Heretic Monkey Aug 15 '18 at 18:26

1 Answers1

0

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>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80