Restrict keyboard character input with jQuery

For validating input, pressed key ASCII code and check it.

If you don’t know the ASCII code of a character then you can view it from here and define your condition in keypress Event handler.

Example

<div class="container">
  <input type='text' id='name' placeholder='Enter your name'><br/><br/>
  <input type='text' id='age' placeholder='Enter your age'>
</div>

<!-- Script -->
<script>
$(document).ready(function(){
  $("#age").keypress(function(e){
    var keyCode = e.which;
    /*
    8 - (backspace)
    32 - (space)
    48-57 - (0-9)Numbers
    */
    if ( (keyCode != 8 || keyCode ==32 ) && (keyCode < 48 || keyCode > 57)) { 
      return false;
    }
  });


  $("#name").keypress(function(e){
    var keyCode = e.which;
 
    /* 
    48-57 - (0-9)Numbers
    65-90 - (A-Z)
    97-122 - (a-z)
    8 - (backspace)
    32 - (space)
    */
    // Not allow special 
    if ( !( (keyCode >= 48 && keyCode <= 57) 
      ||(keyCode >= 65 && keyCode <= 90) 
      || (keyCode >= 97 && keyCode <= 122) ) 
      && keyCode != 8 && keyCode != 32) {
      e.preventDefault();
    }
  });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *