在Javascript中引领“000”输入

时间:2015-01-06 18:06:24

标签: javascript

parseInt("09", 10) // 9 in this way it will just remove the leading 0 

但我想创建一个程序,如果用户输入带前导零的数字,输出将无效

2 个答案:

答案 0 :(得分:1)

function test(input) {
    return !/^0.*[0-9]/.test(input);
}

// false
console.log( test("01") );

// true
console.log( test("1") );

// false
console.log( test("00") );

// true
console.log( test("0") );

答案 1 :(得分:1)

//您可以验证' 0',' 0.2'或者' 2.00'这个正则表达式:

function validDigits(str){
   return /^(0|[1-9]\d*)(\.\d+)?$/.test(str)? 'valid':false;
}

//测试:

['100', '1.0','0.5','05','0','2.0','002','2.00'].map(function(itm){
return itm+': '+ validDigits(itm);
}).join('\n')

/*  returned value: (String)
100: valid
1.0: valid
0.5: valid
05: false
0: valid
2.0: valid
002: false
2.00: valid
*/