admin管理员组

文章数量:1290960

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=".1.1/jquery.min.js"></script>

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

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./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?

Share Improve this question edited May 20, 2019 at 11:10 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 10, 2015 at 6:43 LearningDeveloperLearningDeveloper 6682 gold badges11 silver badges24 bronze badges 8
  • Make sure to validate your field before using its value. You can still enter an alphabetic character in that field. – Sebastian Simon Commented Sep 10, 2015 at 6:53
  • jsfiddle/arunpjohny/672qc1q3/1 – Arun P Johny Commented Sep 10, 2015 at 6:53
  • @ArunPJohny Replace /a-z/i by /[a-z]/i in your fiddle. – Sebastian Simon Commented Sep 10, 2015 at 6:55
  • 3 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... – Adriano Repetti Commented Sep 10, 2015 at 6:56
  • 2 @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. – Adriano Repetti Commented Sep 10, 2015 at 7:31
 |  Show 3 more ments

5 Answers 5

Reset to default 2

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./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 mas 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 mas
    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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

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'

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]/ );

If you are trying for only alphabet with space you can try it:

$("#test").on("keypress keyup blur",function (event) { 

 $(this).val($(this).val().replace(/[^a-zA-Z ]/, ""));

if (!((event.charCode > 64 && 
    event.charCode < 91) || event.charCode ==32 || (event.charCode > 96 && 
      event.charCode < 123))) {
      event.preventDefault();
    }
 });

This code will allow only numbers to be accepted for example in a telepone number input field. This is the improvement on the accepted answer.

var regExp = /[0-9]/;
      $("#test").on('keydown keyup blur focus', function(e) {

        var value =e.key;
        /*var ascii=value.charCodeAt(0);
        $('textarea').append(ascii);
        $('textarea').append(value);
        console.log(e);*/
        // Only numbers
        if (!regExp.test(value)
          && e.which != 8   // backspace
          && e.which != 46  // delete
          && (e.which < 37  // arrow keys
            || e.which > 40)) {
              e.preventDefault();
              return false;
        }
      });

本文标签: javascriptjQuery do not allow alphabets to be entered in input fieldStack Overflow