在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

当前回答

我找到了简单的解决方案,可能不是最好的,但效果很好:)

所以,我接下来要做的是,将字符串解析为Int,并检查新变量的长度大小(现在是Int类型)是否和原始字符串变量的长度相同。从逻辑上讲,如果大小相同,则意味着字符串被完全解析为int,并且只有当字符串仅由数字“构成”时,这才是可能的。

var val=1+$(e).val()+'';
var n=parseInt(val)+'';
if(val.length == n.length )alert('Is int');

您可以很容易地将该代码放在函数中,如果int,则使用return true代替alert。记住,如果您在字符串中使用点或逗号,您将检查它是否仍然为false,因为您正在解析为int。

注意:在e.val上添加1+,因此不会删除起始零。

其他回答

以下方法也可能奏效。

function isNumeric(v) {
         return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
   };

对我来说,这是最好的方式:

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

最好的方法如下:

function isThisActuallyANumber(data){
    return ( typeof data === "number" && !isNaN(data) );
}

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

如果typeof n==“string”,则需要检查空/未定义条件并删除逗号(对于美国数字格式)。

function isNumeric(n)
{
    if(n === null || typeof n === 'undefined')
         return false;

    if(typeof n === 'string')
        n = n.split(',').join('');

    return !isNaN(parseFloat(n)) && isFinite(n);
}

https://jsfiddle.net/NickU/nyzeot03/3/