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

How to Restrict HTML Text Input to Numeric Values Only?

Patricia Arquette
Release: 2024-12-17 05:35:25
Original
381 people have browsed it

How to Restrict HTML Text Input to Numeric Values Only?

How to Allow Only Numeric Input in HTML Text Input Field

One can leverage JavaScript's setInputFilter function to restrict user input within text input fields to numeric characters and decimal points ('.'):

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)) {
                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")) {
                this.classList.add("input-error");
                this.setCustomValidity(errMsg);
                this.reportValidity();
                this.value = this.oldValue;
                this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
            } else {
                this.value = "";
            }
        });
    });
}
Copy after login

To enforce numeric input, use the following filter:

setInputFilter(document.getElementById("myTextBox"), function (value) {
    return /^\d*\.?\d*$/.test(value); 
});
Copy after login

This filter validates input against the regular expression ^d*.?d*$, which accepts strings containing only digits, decimal points, or a combination of both.

The above is the detailed content of How to Restrict HTML Text Input to Numeric Values Only?. 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