allow only numeric input text

How to Allow only Numeric Input in HTML Text Input

JavaScript text inputs are often used in HTML forms to accept user input. Many times you may want to limit user input to only numbers in text inputs. In this article, we will learn how to allow only numeric input in HTML text input.


How to Allow only Numeric Input in HTML Text Input

You will need to define a custom JavaScript function that listens to your text input, parses the entered value and displays an error message if user input is not numeric. You can do this many ways. We will learn how to do this using plain JavaScript, jQuery and HTML. Let us say you have the following text input.

<input type='text' id='myText'/>

1. Using Inline Event Handler (Simple)

If you are looking for a simple validator that checks user input when it is typed, you can attach an event handler to onkeydown event of text input as shown below. It basically checks user input against a regular express for numbers, using test() function and returns the result.

<input type='text' id='myText' onkeydown="return /[0-9]/i.test(event.key)" />


2. Using JavaScript (Advanced)

Here is a function for this purpose.

// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
    textbox.addEventListener(event, function(e) {
      if (inputFilter(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          this.classList.remove("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        this.classList.add("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  });
}

Let us look at the above function in detail. It basically listens to input, keydown, keyup, mousedown, mouseup, select, contextmenu, drop, focusout events for the input text. It basically restores the old value i case there is an erroneous input.

You can attach this function to your textbox as shown below.

setInputFilter(document.getElementById("myText"), function(value) {
  return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");

The above function attaches setInputFilter to your textbox. When a user enters input text, it uses test() function to check if it is a number or not. If it is not a number, it displays an error message and restores the old value. If it is a number then it updates the text with new value.

You can also add following CSS to your page so that a red box is displayed whenever user input is non numeric.

.input-error{
  outline: 1px solid red;
}

This method supports supports Copy & Paste via keyboard input, keyboard shortcuts, context menu operations such as Copy-Paste, non-typeable keys, combination keys such as caret & dollar.


3. Using HTML

HTML browsers make it supereasy to check if input text is number or not.

<input type="number">

But please note, this method checks the user input only at the time of form submissions and not when user is typing input, as happens in the previous method.


4. Using jQuery

You can also use jQuery library to validate text input to be numeric. Here is the setInputFilter() function defined in method #1 above, modified for jQuery.

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(callback, errMsg) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
      if (callback(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          $(this).removeClass("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        $(this).addClass("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  };
}(jQuery));

Here is how to attach the function to your text input.

$(document).ready(function() {
  $("#myText").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  },"Only digits allowed");
});

This functions works the same way as the one described in method 1.

In this article, we have learnt how to allow numeric input in text input in HTML.

Also read:

How to Disable Scrolling in HTML/JavaScript
How to Change Sudo Password Timeout in Linux
How to Reset WordPress Admin Password via MySQL
How to Stop SetInterval Call in JavaScript
How to Store File Content in Shell Variable

Leave a Reply

Your email address will not be published. Required fields are marked *