我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。

我如何使用jQuery做到这一点?


当前回答

下面是另一种方法。这也可以用于粘贴。[用于字母-数字验证]

//Input Validation
var existingLogDescription = "";

$('.logDescription').keydown(function (event) {
    existingLogDescription = this.value;

});


$('.logDescription').keyup(function () {
    if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
        alert("Log Description should contain alpha-numeric values only");
        this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
        this.value = existingLogDescription;
    }
});

其他回答

重构了已接受的答案,因此不再需要使用注释,因为我讨厌注释。这也更容易用茉莉花进行测试。

    allowBackspaceDeleteTabEscapeEnterPress: function(event){
    return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
    return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
    return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
    return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
            || this.allowContorlAPress(event)
            || this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
    return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
    return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
   return (event.shiftKey
           || (this.isNotFromTopRowNumberKeys(event)
                && this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
    $('.myinputclassselector').keydown(function (event) {
        if(this.validateKeyPressEvent(event)) return false;
    });
},
validateKeyPressEvent: function(event){
    if(this.theKeyPressedIsEditRelated(event)){
        return;
    } else {
        if (this.theKeyIsNonNumeric(event)) {
            event.preventDefault();
        }
    }
}

检查小数点是否已经使用:-

        // Stop: Multiple decimal points
        if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
            e.preventDefault(); 

需要确保你有数字键盘和tab键工作

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

只需要在Jquery中应用此方法,您可以验证您的文本框只接受数字。

function IsNumberKeyWithoutDecimal(element) {    
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp); 
}

试试这个解决方案

我认为这对每个人都有帮助

  $('input.valid-number').bind('keypress', function(e) { 
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
  })