有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

对于喜欢说俏皮话的人。

string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

我在输入type="text"上使用这段代码,并使用AngularJS在按键时激活,但如果喜欢,可以使用jQuery。只需将此代码放入一个函数中,该函数以某种方式通过按键激活。

它只允许数字,数字+十进制,数字+十进制+数字。

CODE

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";

testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";

testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";

testFour = "622632463.23464236326324363"
=> "622632463.23";

这是为美国货币构建的,但它可以更改为允许超过两个小数点后的第一个小数,如下所示…

改变了代码

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');

testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";

:)

其他回答

我用完了这个函数:

onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"

这在IE和Chrome中工作得很好,我不知道为什么它在firefox中也不工作得很好,这个功能在firefox中阻止了tab键。

对于tab键在firefox中工作很好,添加这个:

onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"

在准备验证任何东西时调用此函数。我在这里使用了一个文本框

在我的HTML中:

<input type="button" value="Check IT!" onclick="check(document.getElementById('inputboxToValidate').value);" />

在JavaScript代码中:

function check(num){
    var onlynumbers = true
    for (var i = 0; i < (num.length - 1); i++) {
        if (num.substr(i, 1) != "0" || num.substr(i, 1) != "1" || num.substr(i, 1) != "2" || num.substr(i, 1) != "3" || num.substr(i, 1) != "4" || num.substr(i, 1) != "5" || num.substr(i, 1) != "6" || num.substr(i, 1) != "7" || num.substr(i, 1) != "8" || num.substr(i, 1) != "9") {
            alert("please make sure that only numbers have been entered in the Quantaty box");
            onlynumbers = false
        }
    }
    if (onlynumbers == true) {

        //Execute Code
    }
}

正则表达式和匹配函数可以很好地处理这种情况。例如,我使用下面的代码来验证图上作为坐标的4个输入框。它运行得相当好。

function validateInput() {
   if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
       jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
         alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
         location.reload();
   }
}

JavaScript

你可以用下面的setInputFilter函数过滤text <input>的输入值(支持复制+粘贴,拖放,键盘快捷键,上下文菜单操作,不可输入键,插入号位置,不同的键盘布局,有效性错误消息,以及ie9以来的所有浏览器):

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

你现在可以使用setInputFilter函数来安装一个输入过滤器:

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

对输入错误类应用您首选的样式。这里有一个建议:

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

请注意,您仍然必须进行服务器端验证!

另一个警告是,这将破坏撤销堆栈,因为它设置了这个。直接价值。 这意味着CtrlZ不能在输入无效字符后撤销输入。

Demo

查看JSFiddle演示以获得更多输入过滤器示例或运行下面的堆栈代码片段:

// Restricts input for the given textbox to the given inputFilter. 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 = ""; } }); }); } // Install input filters. setInputFilter(document.getElementById("intTextBox"), function(value) { return /^-?\d*$/.test(value); }, "Must be an integer"); setInputFilter(document.getElementById("uintTextBox"), function(value) { return /^\d*$/.test(value); }, "Must be an unsigned integer"); setInputFilter(document.getElementById("intLimitTextBox"), function(value) { return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500); }, "Must be between 0 and 500"); setInputFilter(document.getElementById("floatTextBox"), function(value) { return /^-?\d*[.,]?\d*$/.test(value); }, "Must be a floating (real) number"); setInputFilter(document.getElementById("currencyTextBox"), function(value) { return /^-?\d*[.,]?\d{0,2}$/.test(value); }, "Must be a currency value"); setInputFilter(document.getElementById("latinTextBox"), function(value) { return /^[a-z]*$/i.test(value); }, "Must use alphabetic latin characters"); setInputFilter(document.getElementById("hexTextBox"), function(value) { return /^[0-9a-f]*$/i.test(value); }, "Must use hexadecimal characters"); .input-error { outline: 1px solid red; } <h2>JavaScript input filter showcase</h2> <p>Supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and <a href="https://caniuse.com/#feat=input-event" target="_blank">all browsers since IE 9</a>.</p> <p>There is also a <a href="https://jsfiddle.net/emkey08/tvx5e7q3" target="_blank">jQuery version</a> of this.</p> <table> <tr> <td>Integer</td> <td><input id="intTextBox"></td> </tr> <tr> <td>Integer &gt;= 0</td> <td><input id="uintTextBox"></td> </tr> <tr> <td>Integer &gt;= 0 and &lt;= 500</td> <td><input id="intLimitTextBox"></td> </tr> <tr> <td>Float (use . or , as decimal separator)</td> <td><input id="floatTextBox"></td> </tr> <tr> <td>Currency (at most two decimal places)</td> <td><input id="currencyTextBox"></td> </tr> <tr> <td>A-Z only</td> <td><input id="latinTextBox"></td> </tr> <tr> <td>Hexadecimal</td> <td><input id="hexTextBox"></td> </tr> </table>

打印稿

下面是它的TypeScript版本。

function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout" ].forEach(function(event) {
    textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & { oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null }) {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      }
      else if (Object.prototype.hasOwnProperty.call(this, "oldValue")) {
        this.value = this.oldValue;
        
        if (this.oldSelectionStart !== null &&
          this.oldSelectionEnd !== null) {
          this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
        }
      }
      else {
        this.value = "";
      }
    });
  });
}

jQuery

还有一个jQuery版本。请看这个答案。

HTML5

HTML5有一个原生的解决方案<input type="number">(参见规范和文档)。文档中有这个输入类型的工作演示。

Instead of reading the value property, read the valueAsNumber property of the input to get the typed value as a number rather than a string. Usage inside a <form> is recommended because validation is made easier this way; for example, pressing Enter will automatically show an error message if the value is invalid. You can use the checkValidity method or the requestSubmit method on the entire form in order to explicitly check the validity. Note that you might need to use the required attribute in order to disallow an empty input. You can use the checkValidity method or the validity property on the input element itself in order to explicitly check the validity. You can use reportValidity to show an error message and use setCustomValidity to set your own message.

这种方法从根本上具有不同的用户体验:允许输入无效字符,并且单独执行验证。 这样做的好处是撤销堆栈(CtrlZ)不会中断。 注意,无论您选择哪种方法,都必须执行服务器端验证。

但请注意,浏览器支持不同:

大多数浏览器只在提交表单时验证输入,而在输入时不验证。 大多数移动浏览器不支持step、min和max属性。 Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e和e。另请参阅问答为什么HTML输入type="number"允许在字段中输入字母e ? Firefox(版本64.0)和Edge (EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。

Demo

document.querySelector("form").addEventListener("submit", (event) => { event.preventDefault(); console.log(`Submit! Number is ${event.target.elements.number.valueAsNumber}, integer is ${event.target.elements.integer.valueAsNumber}, form data is ${JSON.stringify(Object.fromEntries(new FormData(event.target).entries()))}.`); }) label { display: block; } <form> <fieldset> <legend>Get a feel for the UX here:</legend> <label>Enter any number: <input name="number" type="number" step="any" required></label> <label>Enter any integer: <input name="integer" type="number" step="1" required></label> <label>Submit: <input name="submitter" type="submit"></label> </fieldset> </form>

你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

然而,你需要绑定到事件,如keyup等。