1
$('#empcontact').blur(function(){
        var stri = $('#empcontact').val();//the input element
        var numbers = "0123456789";
        var flag = false;
        for(var x=0;x<stri.length;x++){
            var ch = stri.charAt(x);
            var n = numbers.indexOf(ch);
            if(n === -1){//why does it always resolve to true            
                flag = true;
                break;
            }
            else{

            }
        }
        if(flag){
            alert("Not a number");
            $('#empcontact').val(" ");
            $('#empcontact').focus();
        }
});

我不知道为什么即使在传递数字时也传递字符时它总是解析为真。

4

6 回答 6

7

您可以使用$.isNumeric(),例如:

var stri = $('#empcontact').val();
console.log( $.isNumeric( stri ) ); //returns true if is number

或者

var stri = $('#empcontact').val();
console.log(typeof stri === 'number' && isFinite(stri) ); //returns true if number

或只有整数

var intsOnly = /^\d+$/,
    stri = $('#empcontact').val();
if(intsOnly.test(stri)) {
   alert('its valid');   
}
于 2013-10-10T04:11:10.580 回答
1

一个javascript解决方案是

if(isNaN(parseInt('a'))){ // replace 'a' with your variable
    flag = true;
    break;
}
于 2013-10-10T04:21:54.247 回答
1

您可以通过以下方式检查号码:

 function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
 }

或者

function isNumber(n){
  return (parseFloat(n) == n);
}

因为IsNumeric在以下情况下会失败:

IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;

IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;

或者,如果您想为此使用 Regexp,则有许多 Regexp 可用:

/^[0-9]+$/

/^\d*$/

[0-9]+(\.[0-9][0-9]?)?
于 2013-10-10T04:23:01.300 回答
0

尝试使用 Number Validation Plugin,它是一个 jQuery 插件,用于执行 HTML 输入数字类型的验证。

https://github.com/prednaxela/jquery.numbervalidation

于 2014-07-19T14:03:16.637 回答
0

对我来说,这似乎是一个很好的正则表达式情况,请使用:

if(stri.match(/^[0-9]*$/)){
    alert("numeric!");
    // do whatever else...
}

$.isNumeric 将允许疯狂的半数字内容,例如0xFFand 2e5

于 2013-10-10T04:11:16.737 回答
0

号码验证

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode != 99 && charCode != 118 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
于 2021-03-16T14:33:42.807 回答