在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

当前回答

如果我没有弄错,这应该匹配任何有效的JavaScript数值,不包括常量(Infinity,NaN)和符号运算符+/-(因为就我而言,它们实际上不是数字的一部分,它们是独立的运算符):

我需要一个令牌化器,将数字发送到JavaScript进行评估不是一个选项。。。它肯定不是最短的正则表达式,但我相信它抓住了JavaScript数字语法的所有细微之处。

/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d)) 
(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i

有效数字包括:

 - 0
 - 00
 - 01
 - 10
 - 0e1
 - 0e01
 - .0
 - 0.
 - .0e1
 - 0.e1
 - 0.e00
 - 0xf
 - 0Xf

无效数字将为

 - 00e1
 - 01e1
 - 00.0
 - 00x0
 - .
 - .e0

其他回答

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

我觉得我的代码很完美。。。

/***@param{string}s*@return{boolean}*/var isNumber=函数{return s.trim()=="" && !isNaN(数字);};

我意识到这一点已经得到了多次回答,但以下是一个不错的人选,在某些情况下可能有用。

需要注意的是,它假设‘.42’不是一个数字,‘4.’不是数字,因此应该考虑到这一点。

function isDecimal(x) {
  return '' + x === '' + +x;
}

function isInteger(x) {
  return '' + x === '' + parseInt(x);
}

isDecimal通过以下测试:

function testIsNumber(f) {
  return f('-1') && f('-1.5') && f('0') && f('0.42')
    && !f('.42') && !f('99,999') && !f('0x89f')
    && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');
}

这里的想法是,每个数字或整数都有一个“规范”字符串表示,每个非规范表示都应该被拒绝。所以我们将其转换为一个数字并返回,看看结果是否为原始字符串。

这些函数是否对您有用取决于用例。一个特点是不同的字符串表示不同的数字(如果两者都通过isNumber()测试)。

这与例如作为对象属性名称的数字相关。

var obj = {};
obj['4'] = 'canonical 4';
obj['04'] = 'alias of 4';
obj[4];  // prints 'canonical 4' to the console.

这种方式似乎很有效:

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

在一行中:

const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);

要测试它:

常量IsNumeric=(num)=>/^-{0,1}\d*\。{0,1}\d+$/.test(num);函数TestIsNumeric(){var结果=“”results+=(IsNumeric('-1')?“通过”:“失败”)+“:IsNumeric('-1')=>true\n”;结果+=(IsNumeric('-1.5')?“通过”:“失败”)+“:IsNumeric('-1.5')=>true\n”;结果+=(IsNumeric(“0”)?“通过”:“失败”)+“:IsNumeric('0')=>true\n”;结果+=(IsNumeric(“0.42”)?“通过”:“失败”)+“:IsNumeric('0.42')=>true\n”;results+=(IsNumeric('.42')?“通过”:“失败”)+“:IsNumeric('.42')=>true\n”;results+=(!IsNumeric('99999')?“通过”:“失败”)+“:IsNumeric(‘99999’)=>false \n”;results+=(!IsNumeric('0x89f')?“通过”:“失败”)+“:IsNumeric('0x89f')=>false \n”;results+=(!IsNumeric('#abcdef')?“通过”:“失败”)+“:IsNumeric('#abcdef')=>false \n”;results+=(!IsNumeric('1.2.3')?“通过”:“失败”)+“:IsNumeric('1.2.3')=>false \n”;results+=(!IsNumeric(“”)?“通过”:“失败”)+“:IsNumeric(“”)=>false \n”;results+=(!IsNumeric('barh')?“通过”:“失败”)+“:IsNumeric('barh')=>false \n”;返回结果;}console.log(TestIsNumeric());.作为控制台包装{最大高度:100%!重要;顶部:0;}

我从那里借来的正则表达式http://www.codetoad.com/javascript/isnumeric.asp.说明:

/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string
function isNumber(n) {
    return (n===n+''||n===n-0) && n*0==0 && /\S/.test(n);
}

解释:

(n===n-0||n===n+'')验证n是数字还是字符串(丢弃数组、布尔值、日期、空值…)。您可以用n替换(n===n-0|| n===n+'')==未定义&&n==null&&(n.constructor==数字||n.constructor==字符串):明显更快,但不那么简洁。

n*0==0验证n是否是有限数,正如isFinite(n)所做的那样。如果您需要检查表示负十六进制的字符串,只需将n*0==0替换为类似于n.toString().replace(/^\s*-/,'')*0==0。当然,它需要一点钱,所以如果你不需要它,就不要使用它。

/\S/.test(n)丢弃空字符串或只包含空格的字符串(这是必要的,因为在这种情况下isFinite(n)或n*0==0返回假阳性)。您可以使用(n!=0||/0/.test(n))而不是\\S/.test(n)来减少对.test(n)的调用次数,也可以使用稍快但不太简洁的测试,例如(n!=0 | |(n+'').indexOf('0')>=0):微小的改进。