6

I have a regular expression that will be matched against the keypress of the user. I'm quite stuck with it.

Here is my current code:

<script type="text/javascript">
    $('input.alpha[$id=tb1]').keydown(function (e) {
        //var k = e.which;
        //var g = e.KeyCode;
        var k = $(this).val();
        //var c = String.fromCharCode(e.which);
        if (k.value.match(/[^a-zA-Z0-9 ]/g)) {
            e.preventDefault();
        }
    });
</script>

The goal here is to prevent the user from typing characters that are inside the regex.

5
  • 2
    "Here is the error message on IE9.": where ? Commented Nov 5, 2012 at 9:32
  • Also why k.value, when k = $(this).val()? Have you checked for duplicates? I am sure there are many similar questions on SO. See this, this, this and many more.. Commented Nov 5, 2012 at 9:34
  • I've been tweaking the codes that's why it's bit messy. What I'm trying to do is if the user pressed a character in the keyboard and it matches the regex it will prevent default. Commented Nov 5, 2012 at 9:38
  • @randelramirez1: Is there something unclear about my answer that I can clarify for you? Commented Nov 5, 2012 at 9:44
  • @randelramirez1 main problem of your script is, that $(this).val() is input's value before key was pressed, that means you don't check last key pressed.. Commented Nov 5, 2012 at 9:49

2 Answers 2

6

Try using the fromCharCode method:

$(document).ready(function () {
  $('#tb1').keydown(function (e) {

    var k = String.fromCharCode(e.which);

    if (k.match(/[^a-zA-Z0-9]/g))
      e.preventDefault();
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

There is just one problem with this. It blocks the backspace key as well.
@MichaelS.Miller If you want to keep backspaces as well, just add \x08 to the regex: /[^a-zA-Z0-9\x08]/g.
4

You use keypress rather than keydown and prevent the default action.

For example, this prevents typing a w into the text input:

$("#target").keypress(function(e) {
  if (e.which === 119) { // 'w'
    e.preventDefault();
  }
});

Live Copy | Source

Update: If it's applying the regex that's giving you trouble:

$("#target").keypress(function(e) {
  if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) {
    e.preventDefault();
  }
});

Live Copy | Source

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.