简体   繁体   中英

Java script validation symbol % must not allow in text field

I am working in javascript. I want to add validation on my text field that only characters are allowed.

along with characters, I allowed left arrow key which has keycode 37. But this is creating problem because keycode of % is also 37. And I dont want to allow % symbol.

Please suggest me how can I differenciate % and left arrow key , because both key code are 37 ?

If you press the 'percent' key the char code is 37, for the 'left arrow'-key it's not 37; eg:

$('#test').keypress(function(oEvent) {
    if (oEvent.charCode == 37) {
        return false;
    }
});

Also see this jsfiddle .

=== UPDATE ===

For additional internet explorer support:

$('#test').keypress(function(oEvent) {
    var iCode = typeof oEvent.charCode == 'number' ? oEvent.charCode : oEvent.keyCode;
    if (iCode == 37) {
        return false;
    }
});

Also see this jsfiddle .

Don't limit the keypresses for validation. People can just copy/paste to overcome that.

You need to use Regex so validate your input.

Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

You should validate your user input after the user submits the form. You can write a function that the form's "onsubmit" attribute runs before the data is submitted to the server, or you can set the form action to "action='javascript:someFunction()'" either way will work. Disallowing keystrokes makes the user interface more complicated and cumbersome for the end user and poses security risks for xss or injection attacks. I would advise checking user input with javascript and returning an error message if it is invalid, then on the server side validating the data once more, and sanitizing the data.

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