tv4free
tv4free

Reputation: 287

Onkeypress, javascript is not validating special character

Javascript function to avoid special characters. It is working as expected with alpha & numbers.only problem is, when i need to include -,. (k >= 188 && k <= 190) - that is not working. what am i doing wrong?

    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || (k >= 188 && k <= 190)|| k == 8 || k == 32 || (k >= 48 && k <= 57));

Upvotes: 0

Views: 1863

Answers (1)

Amaresh
Amaresh

Reputation: 11

This is my latest code,it will support all the browser. function isAlphaNumeric(evtGet) {

    var browser = navigator.appName;
    if (browser == "Microsoft Internet Explorer" || browser == "Mozilla Firefox") {
        var keyGet = evtGet.keyCode;
    } else {
        var keyGet = evtGet.which; //(window.Event) ? evtGet.which : evtGet.keyCode;
    }
    alert(keyGet);
        if ((keyGet > 47 && keyGet < 58) || (keyGet > 64 && keyGet < 91) || (keyGet > 96 && keyGet < 123) || (keyGet == 9) || (keyGet == 32) || (keyGet == 8) || (keyGet == 0) || (keyGet == 13)||(keyGet==110))
            return;
        else
            if (browser == "Microsoft Internet Explorer" || browser == "Mozilla Firefox")
            window.event.returnValue = null;
        else
            evtGet.preventDefault();
}

put the above code in the header of the jsp

and call from input field like onKeyPress="return isAlphaNumeric(event,this.value);">

suppose you want to change in the code as per your requirement,there is a alert box please run the code 1st then click on the key board it will show keycode as per your requirement

example-you want to enter (.)in the field it will show you keycode for dot id 47 and you can write (keyGet==47)

Upvotes: 1

Related Questions