Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 995
Ashwin Avatar asked Nov 16 '25 12:11

Ashwin


1 Answers

[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;
}
like image 147
KooiInc Avatar answered Nov 18 '25 13:11

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!