使用jquery进行数字验证

Gan*_*ede 1 jquery function

$('#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();
        }
});
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它总是解析为true,即使在传递字符时传递数字也是如此.

Sud*_*oti 7

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

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

要么

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

或者只有整数

var intsOnly = /^\d+$/,
    stri = $('#empcontact').val();
if(intsOnly.test(stri)) {
   alert('its valid');   
}
Run Code Online (Sandbox Code Playgroud)