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
Patricia ArquetteOriginal
2024-12-17 05:35:25389browse

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 = "";
            }
        });
    });
}

To enforce numeric input, use the following filter:

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

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!

Statement:
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