admin管理员组

文章数量:1325713

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).

EDIT - Added code

 <input type="text" onkeypress="return checkInput();">
    function checkInput(){
        return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
    }

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).

EDIT - Added code

 <input type="text" onkeypress="return checkInput();">
    function checkInput(){
        return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
    }
Share Improve this question edited Jun 23, 2021 at 15:54 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 4, 2011 at 3:39 Timothy RuhleTimothy Ruhle 7,59710 gold badges44 silver badges68 bronze badges 6
  • 7 -1 because you've confused w3schools with a w3c site. I promise to remove the -1 if you correct your answer (I know i could edit it, but then there's the chance that you wouldn't understand why. – zzzzBov Commented Apr 4, 2011 at 3:44
  • I know that w3c schools isn't the best, but it was the best example i could find for my question – Timothy Ruhle Commented Apr 4, 2011 at 3:49
  • @Timothy Ruhle, w3schools is in no way related to the W3C. Please read w3fools a little more. – zzzzBov Commented Apr 4, 2011 at 3:54
  • -1 for not reading zzzBov's first ment. Will remove it if you correct your answer. – awm Commented Apr 4, 2011 at 3:55
  • Then please press save so we can see it! – awm Commented Apr 4, 2011 at 3:59
 |  Show 1 more ment

5 Answers 5

Reset to default 2

Just change the regex in the example to something like this:

numcheck = /[^a-z0-9_-]/;

Or better yet, avoid the double negative with:

numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);

Then you can look up the keycodes of backspace, etc. and check for them too:

if (keychar === 8) return true;
...

Or even put them in your regex:

numcheck = /[a-z0-9_\x08-]/;

You haven't provided any code samples, so it's hard to be specific in a response, but as a general strategy, try this: instead of trying to whitelist characters that can be input while they are being typed in, validate the contents of the text box after every key stroke to make sure that it still contains valid characters. If it doesn't, remove the last character entered.

This approach will allow special keys like backspace, etc., while at the same time achieve what it sounds like you are really after: a valid value in the text box.

Yes you can limit the input of characters. For example create a function that checks what is going on, return true if everything is OK and false if not:

// return true for 1234567890A-Za-z - _
function InputCheck(e) {
    if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        if (e.which == 45 || e.which == 95 || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122))
            return true;
        return false;
    }
    return true;
}

once you have the function, hook it into you input (this is with jQuery):

$('#InputID').keypress(InputCheck);

You can make as plicated a check as you want, for example this will allow for USD money values:

function InputCheck(e) {
    if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46 && e.which != 36) {
        return false;
    }
    // . = 46
    // $ = 36
    var text = $(this).val();

    // Dollar sign first char only
    if (e.which == 36 && text.length != 0) {
        return false;
    }

    // Only one decimal point
    if (e.which == 46 && text.indexOf('.') != -1) {
        return false;
    }

    // Only 2 numbers after decimal
    if (text.indexOf('.') != -1 && (text.length - text.indexOf('.')) > 2) {
        return false;
    }

    return true;
}

You can press any key you like, as long as you keep the value from including anything not in the white-list.

inputelement.onkeyup=function(e){
  e=e || window.event;
  var who=e.target || e.srcElement;
  who.value= who.value.replace(/[^\w-]+/g,'');
}

Add this code to onkeypress event.

    var code;
    document.all ? code = e.keyCode : code = e.which;
    return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));

For browser patibility, You can add var k = e.keyCode == 0 ? e.charCode : e.keyCode;

本文标签: dom eventsJavascript limit text input charactersStack Overflow