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

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

在此先感谢… :)

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

我建议使用此function:

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

使用isNaNfunction检查号码

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

要么

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

  

上面代码的输出将是:

 false false true true 

可以使用下面的代码。 我不会完全依赖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"); }); 
 function isDigit(num) { if (num.length>1){return false;} var string="1234567890"; if (string.indexOf(num)!=-1){return true;} return false; } 

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

使用标准的javascript函数

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