RegEx for Javascript alphanumeric not working as expected

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 intended script should prevent the user from entering a special character inside the username field. The problem is that this script allows printing alphanumeric characters and blocks `~ _ + - = [] {} \ | ;: '", <.> /?

I need this to also block and! @ # $% ^ & * () symbols.

What am I doing wrong? I am testing this with the latest Chrome browser.

EDIT I know this is not the best way to validate the username, but I am asking why the regex is not showing the correct behavior.

jsFiddle click here

+3


source to share


2 answers


keydown

only the one that was pressed by the actual key on the keyboard will be logged, not the entered character, for example. on the imperial keyboard %

is entered shift+5

, so keydown

will only raise the key 5

and therefore accept the input.

Instead, you should keypress

:



$(document).ready(function () {
    $('#txtUsername').keypress(function (evt) {
        if (/^[a-z0-9]+$/i.test(String.fromCharCode(evt.keyCode)) == false) {
            evt.returnValue = false;
            return false;
        }
    });
});

      

Updated script

+2


source


Use event keypress

instead keydown

. When you use keydown

, input is @treated as a press Shiftfollowed by 2, and 2

resolved by a regular expression. keypress

gets the combined key codes.

Also evt.returnValue

deprecated. The correct way to prevent a 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" />
      

Run codeHide result


+3


source







All Articles