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


How do I block special characters from being typed into an input field with jquery?

5/21/2009 11:31:02 PM

I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.

$('input').on('input', function() {
  $(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));

As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.

$('input').on('input', function() {
  var c = this.selectionStart,
      r = /[^a-z0-9]/gi,
      v = $(this).val();
  if(r.test(v)) {
    $(this).val(v.replace(r, ''));
  this.setSelectionRange(c, c);

Short answer: prevent the 'keypress' event:

    var charCode = !e.charCode ? e.which : e.charCode;

    if(/* Test for special character */ )

Long answer: Use a plugin like jquery.alphanum

There are several things to consider when picking a solution:

  • Pasted text
  • Control characters like backspace or F5 may be prevented by the above code.
  • é, í, ä etc
  • Arabic or Chinese...
  • Cross Browser compatibility

I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:


Or for more fine-grained control, add some settings:

    allow      : "€$£",
    disallow   : "xyz",
    allowUpper : false

Hope it helps.


Use HTML5's pattern input attribute!

<input type="text" pattern="^[a-zA-Z0-9]+$" />

Your textbox:

<input type="text" id="name">

Your javascript:

$("#name").keypress(function(event) {
    var character = String.fromCharCode(event.keyCode);
    return isValid(character);     

function isValid(str) {
    return !/[~`[email protected]#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);

Take a look at the jQuery alphanumeric plugin.

//All of these are from their demo page
//only numbers and alpha characters
//only numeric
//only numeric and the .
//all alphanumeric except the . 1 and a

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]