在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

当前回答

如果您希望让数值函数的预测值隐式严格(例如,不解析字符串),那么这应该会奏效。

function isNumeric(n, parse) {
    var t = typeof(n);
    if (parse){
        if (t !== 'number' && t !=='string') return false;
        return !isNaN(parseFloat(n)) && isFinite(n);
    }else{
        if (t !== 'number') return false;
        return !isNaN(n) && isFinite(n) && !_.isString(n);
    }
}

function isInteger(n, parse) {    
    return isNumeric(n, parse) && n % 1 === 0;
}

function isFloat(n, parse) {
    return isNumeric(n, parse) && n % 1 !== 0;
}

如果您希望代码解析字符串,那么只需在parse参数中传递true即可。

这是对下划线contrib方法的修改,该方法隐式宽松,尝试解析字符串,甚至为isNumeric([1])返回true,这可能是人们真正的陷阱。我上面的方法也会更快,因为它只在parse=true时调用parseFloat()。

其他回答

如果需要验证一组特殊的小数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;
}

@Zoltan Lengyel在@CMS 12月的回答(2009年2月,5:36)中对“其他地区”的评论(4月26日,2:14):

我建议测试typeof(n)==“string”:

    function isNumber(n) {
        if (typeof (n) === 'string') {
            n = n.replace(/,/, ".");
        }
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

这扩展了Zoltans的建议,使其不仅能够测试“本地化数字”,如isNumber('12,50'),还可以测试“纯”数字,如isNumber(2011)。

通过利用语言的动态类型检查,一个简单而干净的解决方案:

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

如果你不在乎空格,你可以删除“如果”

参见下面的测试用例

函数IsNumeric(字符串){if(string==''.repeat(string.length)){return false}返回字符串-0===string*1}console.log('-1'+'→ ' + IsNumeric('-1'))console.log('-1.5'+'→ ' + IsNumeric('-1.5'))console.log(“0”+“→ ' + IsNumeric(“0”)console.log(“0.42”+“→ ' + IsNumeric(“0.42”)console.log('.42'+'→ ' + IsNumeric('.42'))console.log('99999'+'→ ' + IsNumeric(“99999”)console.log('0x89f'+'→ ' + IsNumeric('0x89f'))console.log('#abcdef'+'→ ' + IsNumeric(“#abcdef”)console.log('1.2.3'+'→ ' + IsNumeric('1.2.3'))console.log(“+”→ ' + IsNumeric(“”))console.log('33'+'→ ' + IsNumeric(“33”)

无需使用额外的库。

const IsNumeric = (...numbers) => {
  return numbers.reduce((pre, cur) => pre && !!(cur === 0 || +cur), true);
};

Test

> IsNumeric(1)
true
> IsNumeric(1,2,3)
true
> IsNumeric(1,2,3,0)
true
> IsNumeric(1,2,3,0,'')
false
> IsNumeric(1,2,3,0,'2')
true
> IsNumeric(1,2,3,0,'200')
true
> IsNumeric(1,2,3,0,'-200')
true
> IsNumeric(1,2,3,0,'-200','.32')
true

我想补充以下内容:

1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true

正十六进制数以0x开头,负十六进制数则以-0x开头。正八进制数从0开始,负八进制数以-0开始。这一条考虑了已经提到的大部分内容,但包括十六进制和八进制数、负科学数、无穷大数,并删除了十进制科学数(4e3.2无效)。

function IsNumeric(input){
  var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
  return (RE.test(input));
}