3

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

3
  • 1
    Instead of Javascript, you may consider using HTML5 for this. Either way, as a reminder, actual validation should always be on the server. Commented Dec 9, 2014 at 21:40
  • I agree of the validation being on the server, but it is a customer requirement. I will need to find a way to do this in Javascript. Commented Dec 9, 2014 at 21:42
  • Regardless of the requirement though, isnt /^[a-z0-9]+$/i is not supposed to allow !@#$%^&*() Commented Dec 9, 2014 at 21:44

2 Answers 2

3

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" />

Sign up to request clarification or add additional context in comments.

Comments

2

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;
        }
    });
});

Updated Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.