在JavaScript中验证十进制数字最干净、最有效的方法是什么?

奖励积分:

清晰解决方案应干净简单。跨平台。

测试用例:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

当前回答

我运行了下面的程序,它通过了所有测试用例。。。

它使用了parseFloat和Number处理其输入的不同方式。。。

function IsNumeric(_in) {
    return (parseFloat(_in) === Number(_in) && Number(_in) !== NaN);
}

其他回答

如果需要验证一组特殊的小数y您可以使用以下简单的javascript:

http://codesheet.org/codesheet/x1kI7hAD

<input type="text" name="date" value="" pattern="[0-9]){1,2}(\.){1}([0-9]){2}" maxlength="6" placeholder="od npr.: 16.06" onchange="date(this);" />

Javascript:

function date(inputField) {        
  var isValid = /^([0-9]){1,2}(\.){1}([0-9]){2}$/.test(inputField.value);   
  if (isValid) {
    inputField.style.backgroundColor = '#bfa';
  } else {
    inputField.style.backgroundColor = '#fba';
  }
  return isValid;
}

整数值可通过以下方式验证:

function isNumeric(value) {
    var bool = isNaN(+value));
    bool = bool || (value.indexOf('.') != -1);
    bool = bool || (value.indexOf(",") != -1);
    return !bool;
};

这种方式更容易、更快!检查所有测试!

我认为parseFloat函数可以完成这里的所有工作。下面的函数通过了此页面上的所有测试,包括isNumeric(Infinity)==true:

function isNumeric(n) {

    return parseFloat(n) == n;
}

雅虎!UI使用此项:

isNumber: function(o) {
    return typeof o === 'number' && isFinite(o);
}

使用函数isNaN。我相信如果你测试!是NaN(你的字符串),它适用于任何这些情况。