Jquery: filter input on keypress

前端 未结 5 749
花落未央
花落未央 2020-12-18 04:45

I have a text field, which will accept only the following characters:

Allowed characters: [a-z 0-9 + # - .]

This is the same filter SO

5条回答
  •  Happy的楠姐
    2020-12-18 04:54

    Alternate Solution

    One thing that might help would be to use the .which field instead. Then simply return false when it doesn't fit. I actually have a huge object full of .which info for all major browsers. It includes arrays you could borrow from it to create something like:

    var alphaNumericNcontrols = [ 8,9,13,16,17,18,19,20,32,33,34,35,36,37,38,39,40,44,45,46,145,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,96,97,98,99,100,101,102,103,104,105 ],
        illegal = {
            reg: [ 106,111,191,220 ],
            shift: [ 56,59,188,190,191,220,222 ]
        }
    
    $(document).on("keydown", "input[type=text]", function(e) {
        var eKey = e.which || e.keyCode;
        if (alphaNumericNcontrols.indexOf(eKey) === -1) return false;
        if (illegal.reg.indexOf(eKey) > -1) return false;
        if (e.shiftKey && illegal.shift.indexOf(eKey) > -1) return false;
    });
    

    See Working Example Here

    Keep in mind my Object is not perfect and there are some updates I probably need to make to it, but i did my best to establish everything from every possible major browser!

提交回复
热议问题