在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
$('.rsval').bind('keypress', function(e){
var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
var keynum = (!window.event) ? e.which : e.keyCode;
var splitn = this.value.split(".");
var decimal = splitn.length;
var precision = splitn[1];
if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); }
if( keynum == 46 ){
if(decimal > 2) { e.preventDefault(); }
}
if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
e.preventDefault();
});
我想补充以下内容:
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));
}
$('.rsval').bind('keypress', function(e){
var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
var keynum = (!window.event) ? e.which : e.keyCode;
var splitn = this.value.split(".");
var decimal = splitn.length;
var precision = splitn[1];
if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); }
if( keynum == 46 ){
if(decimal > 2) { e.preventDefault(); }
}
if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
e.preventDefault();
});