0

In my project, I have to prevent the user form entering the following chars in the text box: !@#$%^&*(). So How to achieve this with JavaScript/Jquery? I am using it in asp.net web application.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tortoise
  • 731
  • 4
  • 10
  • 21
  • I might suggest that in this case, like many but not all validation cases, it may be better to have a set of allowed characters rather than a set of prohibited ones. – Jon Hanna Mar 25 '11 at 13:23

4 Answers4

0

Use regular expression and/or jQuery validation plugin on client side. However you should validate your stuff also on server side.

yojimbo87
  • 65,684
  • 25
  • 123
  • 131
0

You can use the following library : jQuery plugin validation

And add a custom method as demoed here Phone US

Hope this helps.

foo
  • 160
  • 4
0
<body>
    <input type="text" id="keys">
    <script>
    var forbidden = /[\!\@\#\$\%\^\&\*\(\)]/g;
    var field = document.getElementById('keys');

    field.addEventListener("keyup", function (evt) {
        var val = field.value;
        if (forbidden.test(val)) {
            field.value = val.replace(forbidden, "");
        }
    }, false);
    </script>
</body>
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
0

Try this a code for each character.

$('input:text').keydown(function(e){
  if(e.shiftKey && (e.keyCode == 192 || e.keyCode == 49 || 
    e.keyCode == 222 || e.keyCode == 52 || e.keyCode == 53 || 
    e.keyCode == 54 || e.keyCode == 55 || e.keyCode == 56 || 
    e.keyCode == 57 || e.keyCode == 48)){
      return false;
  }
})

You could try how do i block or restrict special characters from input fields with jquery?

Oh yes and validate your input on the server side as well

Abela
  • 1,225
  • 3
  • 19
  • 42
Alistair Laing
  • 983
  • 1
  • 7
  • 18