Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I block or restrict special characters from input fields with jquery?

People also ask

How do I limit the number of characters in an input field using jQuery?

Limit character input in the textarea including count. JavaScript Code : var maxLength = 15; $('textarea'). keyup(function() { var textlen = maxLength - $(this).

How do you restrict special characters in a textbox using regular expression?

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/; if(address. match(nospecial)){ alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed'); return false; but it is not working.


A simple example using a regular expression which you could change to allow/disallow whatever you like.

$('input').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

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, ''));
});

Edit:
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, ''));
    c--;
  }
  this.setSelectionRange(c, c);
});

Short answer: prevent the 'keypress' event:

$("input").keypress(function(e){
    var charCode = !e.charCode ? e.which : e.charCode;

    if(/* Test for special character */ )
        e.preventDefault();
})

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:

$("input").alphanum();

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

$("#username").alphanum({
    allow      : "€$£",
    disallow   : "xyz",
    allowUpper : false
});

Hope it helps.


Use HTML5's pattern input attribute!

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

Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.

$('#input').bind('keydown', function (event) {
        switch (event.keyCode) {
            case 8:  // Backspace
            case 9:  // Tab
            case 13: // Enter
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down
            break;
            default:
            var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
            var key = event.key;
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
            break;
        }
});

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 !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}