简体   繁体   中英

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.

Add an id to the input (eg '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;
}

JSFiddle

Try

/[-!$%^&*()_+|~=`\\#{}\[\]:";'<>?,.\/]/.test(your_variable)

It returns true if there is a match.

How about just using an additional if clause? Something like...

key.charCodeAt(0) > 32

So...

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) && key.charCodeAt(0) > 32) {
        e.returnValue = false;
        if(e.preventDefault) {
            e.preventDefault();
        }
    }
}

To overcome the problem that for example the left arrow key produces the same key value as the % key, you could use

function validate(e) {
    e = e || window.event;
    var bad = /[^\sa-z\d]/i,
        key = String.fromCharCode( e.keyCode || e.which );   

    if ( e.which !== 0 && e.charCode !== 0 && bad.test(key) ) {
        e.returnValue = false;
        if ( e.preventDefault ) {
            e.preventDefault();
        }
    } 
 }   

Any printable character should produce a non-zero e.which and e.charCode value.
See JavaScript Madness: Keyboard Events .

jsFiddle .

The above assumes spaces are valid - if not, just remove the \\s from the negated character class.

This Worked for Me. Prevent Users from Entering Special Characters(Except Backspace etc)

PatternValidation(e){

    if(!e.key.match(/^[a-zA-Z0-9]*$/))
       {
         e.preventDefault();
       }
},

This is triggered through binding html attribute with keydown event handler

<input type="text" onkeydown="PatternValidation($event)">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM