4

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.

Ashwin
  • 12,081
  • 22
  • 83
  • 117
  • take a look on this http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Kotzilla Mar 06 '13 at 09:36

5 Answers5

6

[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;
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Really? It must be an old version of Mozilla then. Works in Firefox 19.0 here, even in IE8. Try using `document.getElementById('validate')` instead of `document.querySelector', or update your browser. – KooiInc Mar 06 '13 at 12:54
  • I have identified the problem. The problem is keyCode -> 35 to 40 are repeated for keys (home, end etc.) for eg # and 'end' are having code 35. Atleast here in my Mozilla 16 ;). – Ashwin Mar 07 '13 at 07:18
  • I see. The code is adjusted, now home/end, left/right, del/backspace also work in FF/Mozilla. – KooiInc Mar 07 '13 at 08:33
  • That's now working. Thank you very much for your continuous effort. – Ashwin Mar 07 '13 at 15:53
  • Hey! I was checking the above code in IE8. It doesn't work. It always return true. Can you please check? – Ashwin Mar 19 '13 at 08:46
  • I'm using IE10. Can't replicate that in IE8/standards mode, it works like expected. Check (especially) the *document mode* (should read: standards) - press F12, see top of the devtools window. – KooiInc Mar 19 '13 at 09:35
  • Tried a few things, but still not able to replicate, sorry. Will try later on other computers. – KooiInc Mar 19 '13 at 14:23
  • Problem detected. Best advise: leave IE8, it's a retarded browser. Anyway, the jsFiddle (@http://jsfiddle.net/KooiInc/fwcfq/) is IE8-proof now I think. Furthermore: beware of the previous version emulators in IE > 8, the don't seem to be accurate. – KooiInc Mar 19 '13 at 15:07
3

Try

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

It returns true if there is a match.

WillyMilimo
  • 447
  • 3
  • 12
1

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();
        }
    }
}
David
  • 8,340
  • 7
  • 49
  • 71
0

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.

MikeM
  • 13,156
  • 2
  • 34
  • 47
0

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)">
Dharman
  • 30,962
  • 25
  • 85
  • 135
ThivankaW
  • 511
  • 1
  • 8
  • 21