0

I have a input type in which i want to prevent the user only to enter alphanumeric values like A-a and 0-9.

I have done this :

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

In this i am facing issue that tab ,right,left and delete keys are not working .What more i have to add in this please help me in this .

Updated Code

$('.name_list').live('keypress', function (event) {
        var regex = new RegExp("^[a-zA-Z0-9\b]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        var charCode = (event.which) ? event.which : event.keyCode;
        var Enteted = String.fromCharCode(event.which).toLowerCase();
        if (charCode != 9 && (charCode != 37 || Enteted !='%') && charCode!=39 && charCode != 46 && !regex.test(key)) {
            event.preventDefault();
            return false;
        }
    });

In this i am facing issue that it is allowing % to be entered .

Developer
  • 6,292
  • 19
  • 55
  • 115

2 Answers2

0

jQuery validate plugin

jQuery.validator.addMethod("alphanumeric", function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
}); 
brandelizer
  • 342
  • 3
  • 17
0

Because you are using this condition:

if (!regex.test(key)) {
   //...
} 

You need to use this condition to check, is they the tab, left arrow, right arrow or delete buttons.

if (key !== 9 && key != 37 && key!=39 && key != 46 && !regex.test(key)) {
vaso123
  • 12,347
  • 4
  • 34
  • 64