javascriptjqueryregexkeycode

javascript regex to disallow all special characters


Here is a fiddle to start - http://jsfiddle.net/zuVpx/1/

Javascript code:

<script>
    function validate(e) {
        var regex = new RegExp("[a-zA-Z0-9]");
        var key = e.keyCode || e.which;
        key = String.fromCharCode(key);

        if(!regex.test(key)) {
            e.returnValue = false;
            if(e.preventDefault) {
                e.preventDefault();
            }
        }
    }
</script>

HTML code:

<input type="text" onkeypress="validate(event)" />

I want only characters and numbers. Keys like backspace, delete, capslock and arrowkeys etc should work.

Thanks in advance.


Solution

  • [old answer, update] KeyboardEvent.charCode and KeyboardEvent.keyCode are deprecated. We should use KeyboardEvent.key.

    document.querySelector(`#validate`).onkeypress = e => /[a-z0-9]/i.test(e.key);
    <input type="text" id="validate">

    Add an id to the input (e.g. 'validate') and use:

    document.querySelector('#validate').onkeypress = validate;
    
    function validate(e) {
            e = e || event;
            return /[a-z0-9]/i.test(
                       String.fromCharCode(e.charCode || e.keyCode)
                   ) || !e.charCode && e.keyCode  < 48;
    }