jquery - validate characters on keypress?

前端 未结 7 1363
既然无缘
既然无缘 2020-12-05 10:25

I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actuall

7条回答
  •  独厮守ぢ
    2020-12-05 10:41

    I found that combining validation on keypress and keyup gives the best results. Key up is a must if you want to handle copy pasted text. It is also a catch all in case of cross browser issues which allow non numeric values into your textbox.

        $("#ZipCode").keypress(function (event) {
    
            var key = event.which || event.keyCode; //use event.which if it's truthy, and default to keyCode otherwise
    
            // Allow: backspace, delete, tab, and enter
            var controlKeys = [8, 9, 13];
            //for mozilla these are arrow keys
            if ($.browser.mozilla) controlKeys = controlKeys.concat([37, 38, 39, 40]);
    
            // Ctrl+ anything or one of the conttrolKeys is valid
            var isControlKey = event.ctrlKey || controlKeys.join(",").match(new RegExp(key));
    
            if (isControlKey) {return;}
    
            // stop current key press if it's not a number
            if (!(48 <= key && key <= 57)) {
                event.preventDefault();
                return;
            }
        });
    
    $('#ZipCode').keyup(function () {
        //to allow decimals,use/[^0-9\.]/g 
        var regex = new RegExp(/[^0-9]/g);
        var containsNonNumeric = this.value.match(regex);
        if (containsNonNumeric)
            this.value = this.value.replace(regex, '');
    });
    

提交回复
热议问题