检查文本框是否仅包含数字 [英] Check if a textbox contains numbers only
本文介绍了检查文本框是否仅包含数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查文本框中是否只包含数字?
How to check if a textbox contains numbers only?
谷歌搜索时我遇到了这个问题。但我想知道 isNumeric
是否可以用于此目的,或者是否有更简单的方法来检查文本框是否具有数值。
While googling I came across this. But I'm wondering if isNumeric
can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert("query is a string");
} else {
alert("query is numeric");
}
推荐答案
您可以检查用户是否在输入和正则表达式上使用更改
事件仅输入数字。
You can check if the user has entered only numbers using change
event on input and regex.
$(document).ready(function() {
$('#myText').on('change', function() {
if (/^\d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});
REGEX:
-
/
:正则表达式的分隔符 -
^
:以 -
\d
:任意数字 -
+
:一个或多个前面的字符 -
$
:结束
/
: Delimiters of regex^
: Starts with\d
: Any digit+
: One or more of the preceding characters$
: End
正则表达式可视化:
如果您只想允许数字,可以使用输入数字
和 pattern
If you want to allow only numbers, you can use input-number
and pattern
<input type="number" pattern="\d+" />
这篇关于检查文本框是否仅包含数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文