【发布时间】:2010-11-19 08:25:57
【问题描述】:
我有一个简单的textbox,用户可以在其中输入号码。
jQuery 是否有一个 isDigit 函数,如果用户输入数字以外的内容,我可以显示一个警告框?
该字段也可以有小数点。
【问题讨论】:
-
所以你的意思是 numbers 而不是 digits ?
标签: javascript jquery validation
我有一个简单的textbox,用户可以在其中输入号码。
jQuery 是否有一个 isDigit 函数,如果用户输入数字以外的内容,我可以显示一个警告框?
该字段也可以有小数点。
【问题讨论】:
标签: javascript jquery validation
我建议使用正则表达式:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
或者按照@Platinum Azure 的建议使用单个正则表达式:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
【讨论】:
/^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/ 如果您愿意,这将允许最后使用小数、符号甚至科学记数法。您可以根据需要删除各个部分(如果您需要帮助确定哪个部分是什么,请使用 Google Perl 样式的正则表达式,但它应该相当直观)。
忘记正则表达式。 JavaScript 有一个内置函数:isNaN():
isNaN(123) // false
isNaN(-1.23) // false
isNaN(5-2) // false
isNaN(0) // false
isNaN("100") // false
isNaN("Hello") // true
isNaN("2005/12/12") // true
就这样称呼吧:
if (isNaN( $("#whatever").val() )) {
// It isn't a number
} else {
// It is a number
}
【讨论】:
有一种更简单的方法可以检查变量是否为整数。您可以使用 $.isNumeric() 函数。例如
$.isNumeric( 10 ); // true
这将返回真,但如果你用一个字符串代替 10,你会得到假。
我希望这对你有用。
【讨论】:
The signature '(value: any): boolean' of '$.isNumeric' is deprecated.ts(6387)
以下脚本可用于检查值是否为有效整数。
function myFunction() {
var a = parseInt("10000000");
if (!isNaN(a) && a <= 2147483647 && a >= -2147483647){
alert("is integer");
} else {
alert("not integer");
}
}
【讨论】:
值验证不是 jQuery 的职责。您可以为此使用纯 JavaScript。我想到的两种方法是:
/^\d+$/.match(value)
Number(value) == value
【讨论】:
==的原因。
使用 jQuery 的 validation 插件,你可以做这样的事情,假设表单被称为 form 并且要验证的值被称为 nrInput
$("form").validate({
errorElement: "div",
errorClass: "error-highlight",
onblur: true,
onsubmit: true,
focusInvalid: true,
rules:{
'nrInput': {
number: true,
required: true
}
});
这也处理十进制值。
【讨论】:
String.prototype.isNumeric = function() {
var s = this.replace(',', '.').replace(/\s+/g, '');
return s == 0 || (s/s);
}
用法
'9.1'.isNumeric() -> 1
'0xabc'.isNumeric() -> 1
'10,1'.isNumeric() -> 1
'str'.isNumeric() -> NaN
【讨论】:
var yourfield = $('fieldname').val();
if($.isNumeric(yourfield)) {
console.log('IM A NUMBER');
} else {
console.log('not a number');
}
JQUERY 文档:
【讨论】:
jQuery 是一组 JavaScript 函数,对吧?因此,您可以使用 JavaScript 的正则表达式支持来验证字符串。如果你愿意,你也可以把它放在一个 jQuery 回调中,因为它们只是采用匿名声明的函数体,而且这些函数仍然是 JavaScript。
【讨论】:
$(document).ready(function () {
$("#cust_zip").keypress(function (e) {
//var z = document.createUserForm.cust_mobile1.value;
//alert(z);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsgzip").html("Digits Only.").show().fadeOut(3000);
return false;
}
});
});
【讨论】: