Randel Ramirez
Randel Ramirez

Reputation: 3761

How do I prevent user from entering specific characters in a textbox using jQuery?

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.

Upvotes: 6

Views: 15203

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

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

Upvotes: 4

Korikulum
Korikulum

Reputation: 2599

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

Upvotes: 6

Related Questions