在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(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 isNumeric(input) {
    var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
    var regex = RegExp(number);
    return regex.test(input) && input.length>0;
}

它似乎在任何情况下都有效,但我可能错了。

knockoutJs内置库验证函数

通过扩展它,该字段得到验证

1) 编号

self.number=ko.obsobservable(numberValue).exextend({number:true});

测试用例

numberValue = '0.0'    --> true
numberValue = '0'      --> true
numberValue = '25'     --> true
numberValue = '-1'     --> true
numberValue = '-3.5'   --> true
numberValue = '11.112' --> true
numberValue = '0x89f'  --> false
numberValue = ''       --> false
numberValue = 'sfsd'   --> false
numberValue = 'dg##$'  --> false

2) 数字

self.number=ko.obsobservable(numberValue).exextend({digit:true});

测试用例

numberValue = '0'      --> true
numberValue = '25'     --> true
numberValue = '0.0'    --> false
numberValue = '-1'     --> false
numberValue = '-3.5'   --> false
numberValue = '11.112' --> false
numberValue = '0x89f'  --> false
numberValue = ''       --> false
numberValue = 'sfsd'   --> false
numberValue = 'dg##$'  --> false

3) 最小值和最大值

self.number=可观察(numberValue).扩展({min:5}).扩展;

此字段仅接受介于5和10之间的值

测试用例

numberValue = '5'    --> true
numberValue = '6'    --> true
numberValue = '6.5'  --> true
numberValue = '9'    --> true
numberValue = '11'   --> false
numberValue = '0'    --> false
numberValue = ''    --> false

如果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/

在这里,我从这个页面收集了“好的”,并将它们放入一个简单的测试模式中,供您自行评估。

对于新手来说,console.log是一个内置函数(在所有现代浏览器中都可用),它允许您将结果输出到JavaScript控制台(仔细查看,您会发现),而不必输出到HTML页面。

var isNumeric = function(val){
    // --------------------------
    // Recommended
    // --------------------------

    // jQuery - works rather well
    // See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html
    return !isNaN(parseFloat(val)) && isFinite(val);

    // Aquatic - good and fast, fails the "0x89f" test, but that test is questionable.
    //return parseFloat(val)==val;

    // --------------------------
    // Other quirky options
    // --------------------------
    // Fails on "", null, newline, tab negative.
    //return !isNaN(val);

    // user532188 - fails on "0x89f"
    //var n2 = val;
    //val = parseFloat(val);
    //return (val!='NaN' && n2==val);

    // Rafael - fails on negative + decimal numbers, may be good for isInt()?
    // return ( val % 1 == 0 ) ? true : false;

    // pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?
    //return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(val);

    // Haren - passes all
    // borrowed from http://www.codetoad.com/javascript/isnumeric.asp
    //var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    //return RE.test(val);

    // YUI - good for strict adherance to number type. Doesn't let stringy numbers through.
    //return typeof val === 'number' && isFinite(val);

    // user189277 - fails on "" and "\n"
    //return ( val >=0 || val < 0);
}

var tests = [0, 1, "0", 0x0, 0x000, "0000", "0x89f", 8e5, 0x23, -0, 0.0, "1.0", 1.0, -1.5, 0.42, '075', "01", '-01', "0.", ".0", "a", "a2", true, false, "#000", '1.2.3', '#abcdef', '', "", "\n", "\t", '-', null, undefined];

for (var i=0; i<tests.length; i++){
    console.log( "test " + i + ":    " + tests[i] + "    \t   " + isNumeric(tests[i]) );
}

要添加的几个测试:

IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false

我想到了这个:

function IsNumeric(input) {
    return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}

解决方案包括:

开头的可选负号一个零,或者一个或多个不以0开头的数字,或者只要后面有一个周期,就不加任何数字后跟一个或多个数字的句点