jQuery do not allow alphabets to be entered in input field

16,193

Solution 1

Replace

var value = $(this).val();

by

var value = String.fromCharCode(e.which) || e.key;

After all, you need to check which key has been pressed before allowing a character to be typed into the field.

Also, make sure the backspace and delete buttons and arrow keys aren’t blocked!

$(function() {
  var regExp = /[a-z]/i;
  $('#test').on('keydown keyup', function(e) {
    var value = String.fromCharCode(e.which) || e.key;

    // No letters
    if (regExp.test(value)) {
      e.preventDefault();
      return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

If your goal is to only accept numbers, dots and commas use this function instead:

$(function() {
  var regExp = /[0-9\.\,]/;
  $('#test').on('keydown keyup', function(e) {
    var value = String.fromCharCode(e.which) || e.key;
    console.log(e);
    // Only numbers, dots and commas
    if (!regExp.test(value)
      && e.which != 188 // ,
      && e.which != 190 // .
      && e.which != 8   // backspace
      && e.which != 46  // delete
      && (e.which < 37  // arrow keys
        || e.which > 40)) {
          e.preventDefault();
          return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Solution 2

You need to store input data somewhere and update it each time user inputs allowed character or reset when disabled

$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]'),
    inputVal = '';

$('#test').on('keydown keyup', function(e) {

    var value = $(this).val();

    // Do not allow alphabets to be entered.
    if (regExp.test(value)) {
        $(this).val(inputVal)
    }
    else{ 
        inputVal = value
    }

}); // End of 'keydown keyup' method.

}); // End of 'document ready'

Solution 3

Create a function that will mask it out

jsfiddle

$.fn.noMask = function(regex) { 
  this.on("keypress", function(e) {
    if (regex.test(String.fromCharCode(e.which))) {
        return false;
    }
  });
}

$("input").noMask ( /[a-zA-Z]/ );
Share:
16,193
LearningDeveloper
Author by

LearningDeveloper

Developer, eager to learn and code

Updated on June 04, 2022

Comments

  • LearningDeveloper
    LearningDeveloper almost 2 years

    My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault() method on both keydown and keyup methods.

    $(function() {
      // Regular Expression to Check for Alphabets.
      var regExp = new RegExp('[a-zA-Z]');
    
      $('#test').on('keydown keyup', function(e) {
    
        var value = $(this).val();
    
        // Do not allow alphabets to be entered.
        if (regExp.test(value)) {
          e.preventDefault();
          return false;
        }
    
      }); // End of 'keydown keyup' method.
    
    }); // End of 'document ready'
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" id="test" name="test" />

    What am I doing wrong? Is there some other way to get this done?

    • Sebastian Simon
      Sebastian Simon over 8 years
      Make sure to validate your field before using its value. You can still enter an alphabetic character in that field.
    • Arun P Johny
      Arun P Johny over 8 years
    • Sebastian Simon
      Sebastian Simon over 8 years
      @ArunPJohny Replace /a-z/i by /[a-z]/i in your fiddle.
    • Adriano Repetti
      Adriano Repetti over 8 years
      You have a very loose concept of alphabetic characters. If you're limited to basic latin characters then yes, it works. However if an Italian, French, German or anyone else will type "à" then your code won't stop him to do it. Instead it'll stop everyone who uses an IME where a single (non alphabetic) character is made by two Unicode code points...
    • LearningDeveloper
      LearningDeveloper over 8 years
      @Xufox, I'm following your example..
    • LearningDeveloper
      LearningDeveloper over 8 years
      @AdrianoRepetti, Yes I will have to change my Regular Expression to allow only numbers rather than NOT allow alphabets.
    • guradio
      guradio over 8 years
      @GauthamPJ if you want only number then go for type numbers
    • Adriano Repetti
      Adriano Repetti over 8 years
      @GauthamPJ don't forget that also digit is a wide concept (2, ٢, ۲, 二, 兩 and 两 are all the same digit but in different alphabets; 2nd and 3rd are different even if look the same). If you need to support only Arabic numbers then yes, go with a simple regex.
  • LearningDeveloper
    LearningDeveloper over 8 years
    Thanks for the solution, but @Xufox has provided a better answer.
  • LearningDeveloper
    LearningDeveloper over 8 years
    I actually need numbers, comma , and dot . character. But the String.fromCharCode() does not return , and . characters properly. Is there a way to validate these characters?
  • Sebastian Simon
    Sebastian Simon over 8 years
    @GauthamPJ Do you need to block or accept numbers, dots and commas?
  • LearningDeveloper
    LearningDeveloper over 8 years
    I need to Accept only Numbers, Dot and Comma. I used an array of required character codes to check for validity. Got it working properly. Thanks again.
  • Sebastian Simon
    Sebastian Simon over 8 years
    @GauthamPJ I’ve edited my answer. Now both cases should be covered.