Javascript 检查文本框是否仅包含数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30323610/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a textbox contains numbers only
提问by Becky
How to check if a textbox contains numbers only?
如何检查文本框是否仅包含数字?
While googling I came across this. But I'm wondering if isNumericcan be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.
在谷歌搜索时,我遇到了这个。但我想知道是否isNumeric可以用于此目的,或者是否有更简单的方法来检查文本框是否具有数值。
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
    alert("query is a string");
} else {
    alert("query is numeric");
}
回答by Tushar
You can check if the user has entered only numbers using changeevent on input and regex.
您可以检查用户是否仅使用change输入事件和正则表达式输入了数字。
$(document).ready(function() {
    $('#myText').on('change', function() {
        if (/^\d+$/.test($(this).val())) {
            // Contain numbers only
        } else {
            // Contain other characters also
        }
    })
});
REGEX:
正则表达式:
- /: Delimiters of regex
- ^: Starts with
- \d: Any digit
- +: One or more of the preceding characters
- $: End
- /: 正则表达式的分隔符
- ^: 以。。开始
- \d: 任何数字
- +: 一个或多个前面的字符
- $: 结尾
Regex Visualization:
正则表达式可视化:
If you want to allow only numbers, you can use input-numberand pattern
如果你只想允许数字,你可以使用input-number和pattern
<input type="number" pattern="\d+" />
回答by Bellash
using pure JS regular expression
使用纯 JS 正则表达式
 var query = document.getElementById('myText').value;
 var isNumeric=query.match(/^\d+$/);
  if(isNumeric){/*...*/}else{/*...*/}
or using html5 control
或使用 html5 控件
 <input type="number" name="quantity" min="1" max="5">
回答by Mox Shah
回答by Amit G
回答by Dipesh Rana
You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...
您可以将文本框的值与数字回归进行匹配以检查它是否仅包含数字,如下面的代码...
if($('#myText').val().match(/^\d+$/)){
// Your code here
}


