Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
Randel Ramirez Avatar asked Nov 05 '12 09:11

Randel Ramirez


2 Answers

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();
  });
});
like image 70
Korikulum Avatar answered Sep 20 '22 02:09

Korikulum


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

like image 23
T.J. Crowder Avatar answered Sep 20 '22 02:09

T.J. Crowder