[Drupal] How to limit a text field to accept only numbers as input?

| | 2 min read

When developing a website we might often come across situations where we have to limit the entry into each text fields to a certain type. One of the common scenarios we run into when developing Drupal websites is to limit text fields to accept only numbers as its input. If you want to know how to limit a text field to accept only numbers as input then read on to find out more.

We are going to limit the text fields using Javascript code.

  • First add the follow Javascript function which will accept the keycodes entered and determine whether it is a number or not.
    function isNumber(event) {
      if (event) {
        var charCode = (event.which) ? event.which : event.keyCode;
        if (charCode != 190 && charCode > 31 && 
           (charCode < 48 || charCode > 57) && 
           (charCode < 96 || charCode > 105) && 
           (charCode < 37 || charCode > 40) && 
            charCode != 110 && charCode != 8 && charCode != 46 )
           return false;
      return true;
  • The if condition written to check the key codes will accept numbers, arrow keys, backspaces and delete key strokes.
  • The condition for the operation can be customized to your choice. Checkout the keycodes used in Javascript to identify keystrokes.
  • This javascript has to be added to the input textfield in the keydown event.
    <input type="text" onkeydown="return isNumber(event);" />

Other key stroke events such as keypress and keyup can be used, but the condition for execution must be changed accordingly. If the above steps are followed correctly then the text field will accept only numbers as input.