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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:59:27  来源:igfitidea点击:

Check if a textbox contains numbers only

javascriptjqueryregex

提问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:

正则表达式:

  1. /: Delimiters of regex
  2. ^: Starts with
  3. \d: Any digit
  4. +: One or more of the preceding characters
  5. $: End
  1. /: 正则表达式的分隔符
  2. ^: 以。。开始
  3. \d: 任何数字
  4. +: 一个或多个前面的字符
  5. $: 结尾

Regex Visualization:

正则表达式可视化:

enter image description here

在此处输入图片说明

Demo

演示



If you want to allow only numbers, you can use input-numberand pattern

如果你只想允许数字,你可以使用input-numberpattern

<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

There're many ways, you can use isNaN

有很多方法,你可以使用isNaN

 isNaN(VALUE);

You can also use regEx to verify numeric values.

您还可以使用 regEx 来验证数值。

console.log(/^\d+$/.test(VALUE));

回答by Amit G

Jquery provides generic util method to handle this. handles numeric/float/hex

Jquery 提供了通用的 util 方法来处理这个问题。处理数字/浮点数/十六进制

$.isNumeric( value )

Try: fiddle

尝试:小提琴

回答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
}