使用 jQuery 验证文本字段是否为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2405880/
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
Validate that text field is numeric usiung jQuery
提问by George Johnston
I have a simple issue -- I would like to check a field to see if it's an integer if it is not blank. I'm not using any additional plugins, just jQuery. My code is as follows:
我有一个简单的问题——我想检查一个字段,如果它不是空白的,它是否是一个整数。我没有使用任何额外的插件,只是 jQuery。我的代码如下:
if($('#Field').val() != "")
{
if($('#Field').val().match('^(0|[1-9][0-9]*)$'))
{
errors+= "Field must be numeric.<br/>";
success = false;
}
}
...It doesn't seem to work. Where am I going wrong?
……好像不行。我哪里错了?
The error I receive is val() is not an object
.
我收到的错误是val() is not an object
。
It turned out that the real issue was that I had my element name set and not the Id.
事实证明,真正的问题是我设置了元素名称而不是 Id。
采纳答案by karim79
This should work. I would trim the whitespacefrom the input field first of all:
这应该有效。我会首先从输入字段中修剪空格:
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.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}
回答by motomod
Regex isn't needed, nor is plugins
不需要正则表达式,也不需要插件
if (isNaN($('#Field').val() / 1) == false) {
your code here
}
回答by Mohit Jain
I know there isn't any need to add a plugin for this.
我知道没有必要为此添加插件。
But this can be useful if you are doing so many things with numbers. So checkout this pluginat least for a knowledge point of view.
但是如果你用数字做很多事情,这会很有用。所以至少从知识的角度检查这个插件。
The rest of karim79's answeris super cool.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="jquery.numeric.js"></script>
</head>
<body>
<form>
Numbers only:
<input class="numeric" type="text" />
Integers only:
<input class="integer" type="text" />
No negative values:
<input class="positive" type="text" />
No negative values (integer only):
<input class="positive-integer" type="text" />
<a href="#" id="remove">Remove numeric</a>
</form>
<script type="text/javascript">
$(".numeric").numeric();
$(".integer").numeric(false, function() {
alert("Integers only");
this.value = "";
this.focus();
});
$(".positive").numeric({ negative: false },
function() {
alert("No negative values");
this.value = "";
this.focus();
});
$(".positive-integer").numeric({ decimal: false, negative: false },
function() {
alert("Positive integers only");
this.value = "";
this.focus();
});
$("#remove").click(
function(e)
{
e.preventDefault();
$(".numeric,.integer,.positive").removeNumeric();
}
);
</script>
</body>
</html>
回答by CrypticGuru
I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/
我不确定何时实施,但目前您可以使用http://api.jquery.com/jQuery.isNumeric/
if($('#Field').val() != "")
{
if($.isNumeric($('#Field').val()) {
errors+= "Field must be numeric.<br/>";
success = false;
}
}
回答by Sadik Ali
All basic validation by using a class:
使用类的所有基本验证:
$('.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 = "";
});
Example:
例子:
<asp:TextBox
runat="server"
ID="txtDeliveryFee"
TextMode="SingleLine"
CssClass="form-control IsInteger"
MaxLength="3"
Text="0"
></asp:TextBox>
Just put the class name in the input.
只需在输入中输入类名即可。
回答by Jijo John
You don't need a regex for this one. Use the isNAN()
JavaScript function.
你不需要这个正则表达式。使用isNAN()
JavaScript 函数。
The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.
isNaN() 函数确定一个值是否为非法数字(Not-a-Number)。如果值为 NaN,则此函数返回 true,否则返回 false。
if (isNaN($('#Field').val()) == false) {
// It's a number
}