jquery:validation文本字段是否为数字

我有一个简单的问题 – 我想检查一个字段,看它是否是一个整数,如果它不是空白。 我没有使用任何额外的插件,只是jQuery。 我的代码如下:

if($('#Field').val() != "") { if($('#Field').val().match('^(0|[1-9][0-9]*)$')) { errors+= "Field must be numeric.
"; success = false; } }

……它似乎不起作用。 我哪里错了?

我收到的错误是val() is not an object

更新:事实certificate,真正的问题是我设置了元素名称而不是Id。

这应该工作。 我首先要从输入字段修剪空格 :

 if($('#Field').val() != "") { var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, ''); var intRegex = /^\d+$/; if(!intRegex.test(value)) { errors += "Field must be numeric.
"; success = false; } } else { errors += "Field is blank."; success = false; }

不需要正则表达式,也不需要插件

 if (isNaN($('#Field').val() / 1) == false) { your code here } 

我知道没有必要为此添加插件。 但是如果你用数字做很多事情,这可能会很有用。 因此,至少从知识的角度来看这个插件。 restkarim79的回答非常酷。

         
Numbers only: Integers only: No negative values: No negative values (integer only): Remove numeric

我不确定这是什么时候实现的,但是目前你可以使用http://api.jquery.com/jQuery.isNumeric/

 if($('#Field').val() != "") { if($.isNumeric($('#Field').val()) { errors+= "Field must be numeric.
"; success = false; } }

按类使用的所有基本validation

 $('.IsInteger,.IsDecimal').focus(function (e) { if (this.value == "0") { this.value = ""; } }); $('.IsInteger,.IsDecimal').blur(function (e) { if (this.value == "") { this.value = "0"; } }); $('.IsInteger').keypress(function (e) { var charCode = (e.which) ? e.which : e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; }); $('.IsDecimal').keypress(function (e) { var charCode = (e.which) ? e.which : e.keyCode; if (this.value.indexOf(".") > 0) { if (charCode == 46) { return false; } } if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; }); $('.IsSpecialChar').keypress(function (e) { if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) return false; else return true; }); $('.IsMaxLength').keypress(function (e) { var length = $(this).attr("maxlength"); return (this.value.length <= length); }); $('.IsPhoneNumber').keyup(function (e) { var numbers = this.value.replace(/\D/g, ''), char = { 0: '(', 3: ') ', 6: ' - ' }; this.value = ''; for (var i = 0; i < numbers.length; i++) { this.value += (char[i] || '') + numbers[i]; } }); $('.IsEmail').blur(function (e) { var flag = false; var email = this.value; if (email.length > 0) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; flag = regex.test(email); } if (!flag) this.value = ""; }); 

例:-

只需将类名放入输入中

你不需要这个正则表达式。 使用isNAN() javascript函数。

isNaN()函数确定值是否为非法数字(非数字)。 如果值为NaN,则此函数返回true,否则返回false。

 if (isNaN($('#Field').val()) == false) { //it's a number }