使用JavaScript / jQuery进行简单的数字验证

时间:2011-04-14 12:21:46

标签: javascript jquery validation

JavaScript / jQuery中是否有任何简单方法来检查变量是否为数字(最好没有插件)?我想提醒变量是否为数字。

提前致谢... :)

5 个答案:

答案 0 :(得分:19)

由于Java Script类型强制,我不建议使用isNaN函数来检测数字。

例如:

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 !!

您还应该记住,isNaN将为浮点数返回false(是数字)。

isNaN('1e1'); // is number
isNaN('1e-1'); // is number

我建议改为使用this函数:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

答案 1 :(得分:4)

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 ");
}

检查号码是否是非法号码:

<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>

上面代码的输出将是:

false
false
true
true 

答案 2 :(得分:1)

可以使用以下代码。我不会完全依赖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");
});

答案 3 :(得分:0)

function isDigit(num) {
    if (num.length>1){return false;}
    var string="1234567890";
    if (string.indexOf(num)!=-1){return true;}
    return false;
}

你需要遍历字符串并为每个字符调用此函数

答案 4 :(得分:0)

使用标准的javascript函数

isNaN('9')// this will return false
isNaN('a')// this will return true