Textbox with alphanumeric check in javascript

后端 未结 5 1159
失恋的感觉
失恋的感觉 2020-12-12 01:37

I have a textbox, and it needs not allow the user to enter any special characters. He can enter:

  1. A-Z
  2. a-z
  3. 0-9
  4. Space.

O

5条回答
  •  佛祖请我去吃肉
    2020-12-12 01:59

    add a onKeyUp="javascript:checkChar(this);" to the input box.

    function checkChar(tBox) {   
    
        var curVal = tBox.value;
    
        if ( /[^A-Za-z0-9 ]/.test(curVal) ) { 
    
            //do something because he fails input test.
    
        }
    
    }
    

    alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:

    onKeyUp="javascript:checkChar(event);"

    function checkChar(e) {
    
        var key;
    
    
        if (e.keyCode) key = e.keyCode;
        else if (e.which) key = e.which;
    
        if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
    
            //fails test
    
        }
    
    }
    

    missed the part about first char, but you can do a test on the textbox value as in the first example:

    /^[A-Za-z]/.test(curVal)
    

    or even use the second method but pass the text box as well so you can get it's full value.

提交回复
热议问题