Reputation: 1957
I have the following script:
$('#txtUsername').keydown( function(evt) {
if (/^[a-z0-9]+$/i.test(String.fromCharCode(evt.keyCode)) == false) {
evt.returnValue = false;
return false;
}
});
The script above is supposed to prevent the user from entering in special character inside the user name field. The problem is that this script allows typing of alphanumeric characters and it blocks `~_+-=[]{}\|;:'",<.>/?
I need this to also block and !@#$%^&*() characters.
What am I doing wrong? I am testing this with latest Chrome browser.
EDIT I know this is not the best way to validate a username, but I am questioning why regex is not showing the correct behavior.
jsFiddle click here
Upvotes: 3
Views: 112
Reputation: 780879
Use the keypress
event, not keydown
. When you use keydown
, entering @ is seen as pressing Shift followed by 2, and 2
is allowed by the regexp. keypress
gets the merged key codes.
Also, evt.returnValue
is deprecated. The proper way to prevent the normal event handler from running is by calling evt.preventDefault()
.
$('#txtUsername').keypress(function(evt) {
if (/^[a-z0-9]+$/i.test(String.fromCharCode(evt.keyCode)) == false) {
evt.preventDefault();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtUsername" />
Upvotes: 3
Reputation: 16609
keydown
will only log which actual key on the keyboard was pressed, not the character which was entered, e.g. on a UK keyboard %
is entered with shift+5
, so keydown
will only pick up the 5
key and so accept the input.
You should keypress
instead:
$(document).ready(function () {
$('#txtUsername').keypress(function (evt) {
if (/^[a-z0-9]+$/i.test(String.fromCharCode(evt.keyCode)) == false) {
evt.returnValue = false;
return false;
}
});
});
Upvotes: 2