Home > Web Front-end > JS Tutorial > How to Restrict HTML Text Input to Only Accept Numeric Values Using JavaScript?

How to Restrict HTML Text Input to Only Accept Numeric Values Using JavaScript?

Linda Hamilton
Release: 2024-12-15 16:50:23
Original
172 people have browsed it

How to Restrict HTML Text Input to Only Accept Numeric Values Using JavaScript?

How to Restrict an HTML Text Input to Only Allow Numeric Input

To implement numeric-only input in an HTML text input field, you can utilize the JavaScript setInputFilter function. This function comprehensively filters input values by supporting:

  • Copy and Paste operations
  • Drag and Drop operations
  • Keyboard shortcuts
  • Context menu actions
  • Non-typeable keys
  • Caret position
  • Different keyboard layouts
  • Validity error messages
  • Compatibility with all browsers back to IE 9

JavaScript Code:

// 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 = "";
      }
    });
  });
}
Copy after login

Using the Function:

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

In this example, the setInputFilter function is used on the "myTextBox" element to allow only numeric values. The inputFilter function uses a regular expression to ensure that the input consists solely of digits or a decimal point.

Important Notes:

  • Server-Side Validation: Note that client-side validation is not sufficient. You must also perform server-side validation for secure input handling.
  • Undo Stack: This solution breaks the undo functionality by directly setting the value. Hence, Ctrl Z will not work for invalid inputs.
  • Style Customization: You can apply styles to the "input-error" class as needed.

The above is the detailed content of How to Restrict HTML Text Input to Only Accept Numeric Values Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template