jquery - validate characters on keypress?

前端 未结 7 1301
既然无缘
既然无缘 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 11:02

    You could try this extension:

    jQuery.fn.ForceAlphaNumericOnly =
    function()
    {
        return this.each(function()
        {
            $(this).keydown(function(e)
            {
                var key = e.charCode || e.keyCode || 0;
                // allow backspace, tab, delete, arrows, letters, numbers and keypad numbers ONLY
                return (
                    key == 8 || 
                    key == 9 ||
                    key == 46 ||
                    (key >= 37 && key <= 40) ||
                    (key >= 48 && key <= 57) ||
                    (key >= 65 && key <= 90) ||
                    (key >= 96 && key <= 105));
            })
        })
    };
    

    Useage:

    $("#yourInput").ForceAlphaNumericOnly();
    
    0 讨论(0)
提交回复
热议问题