使用 JavaScript / jQuery 进行简单的数字验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5663141/
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
Simple number validation using JavaScript / jQuery
提问by blasteralfred Ψ
Is there any simple method in JavaScript / jQuery to check whether the variable is a number or not (preferably without a plugin)? I want to alert whether the variable is a number or not.
JavaScript / jQuery 中是否有任何简单的方法来检查变量是否为数字(最好没有插件)?我想提醒变量是否为数字。
Thanks in advance...:)
提前致谢...:)
回答by Corneliu
I wouldn't recommend the isNaN
function to detect numbers, because of the Java Script type coercion.
isNaN
由于 Java Script 类型强制,我不推荐使用该函数来检测数字。
Ex:
前任:
isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!
You should also bear in mind that isNaN
will return false (is number) for floating point numbers.
您还应该记住,isNaN
浮点数将返回 false(是数字)。
isNaN('1e1'); // is number
isNaN('1e-1'); // is number
I would recommend to use thisfunction instead:
我建议改用这个函数:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
回答by Pranay Rana
Checking number using isNaN function
var my_string="This is a string";
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}
or
或者
Check whether a number is an illegal number:
检查一个号码是否是非法号码:
<script type="text/javascript">
document.write(isNaN(5-2)+ "<br />");
document.write(isNaN(0)+ "<br />");
document.write(isNaN("Hello")+ "<br />");
document.write(isNaN("2005/12/12")+ "<br />");
</script>
The output of the code above will be:
上面代码的输出将是:
false
false
true
true
回答by Mrinal Jha
Can use below code for this. I would not rely on isNaN() completely. isNaN has shown inconsistent results to me (e.g - isNaN will not detect blank spaces.).
可以为此使用以下代码。我不会完全依赖 isNaN()。isNaN 向我显示了不一致的结果(例如 - isNaN 不会检测空格。)。
//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
// Get the non Numeric char that was enetered
var nonNumericChars = $(this).val().replace(/[0-9]/g, '');
if(nonNumericChars.length > 0)
alert("Non Numeric Data entered");
});
回答by anupam
function isDigit(num) {
if (num.length>1){return false;}
var string="1234567890";
if (string.indexOf(num)!=-1){return true;}
return false;
}
You need to loop through the string and call this function for every character
您需要遍历字符串并为每个字符调用此函数
回答by Mamoon ur Rasheed
use standard javascript functions
使用标准的 javascript 函数
isNaN('9')// this will return false
isNaN('a')// this will return true