Skip to content Skip to sidebar Skip to footer

Limiting Input To Specified Regexp With Uppercase Chars In Ie

I'm trying to limit what our users will be able to type in inputs, using javascript/jquery. Problem is, I have to limit this to Uppercase chars only, and numbers. Here's what I cod

Solution 1:

Use the keypress() event instead. In IE, all keydown and keyup specify which keyboard key code was pressed -- it doesn't take control keys into account and modify the keycode accordingly. The keypress event specifies which character code was typed. Be aware that it will not work for certain system keys:

As of Microsoft Internet Explorer 4.0, the onkeypress event fires and can be canceled for the following keys:
  • Letters: A - Z (uppercase and lowercase)
  • Numerals: 0 - 9
  • Symbols: ! @ # $ % ^ & * ( ) _ - + = System: ESC, SPACEBAR, ENTER

Since your edit -- you need to use e.which instead of e.charCode.

Solution 2:

From the jquery manual for keypress():

To determine which character was entered, we can examine the event object that is passed to the handler function. While browsers use differing attributes to store this information, jQuery normalizes the .which attribute so we can reliably use it to retrieve the character code.

In other words, if you are using jquery, you are safe to use e.which to return the character code, so in your case:

varchar = String.fromCharCode(e.which);

is the change to make.

But personally, I would avoid punishing users for lower-case input by converting it for them. Maybe add this modification:

$("input.populationReference").keypress(function(e){
                        varValidPattern = /^[A-Z_a-z_0-9]*$/;
                        var char = String.fromCharCode(e.charCode);
                        if (!ValidPattern.test(char) && e.charCode!=0){
                            returnfalse;
                            e.preventDefault();
                        } else {
                          var inputval = $(this).value(); 
                          $(this).value(inputval.toUpperCase());
                        }
                });

Solution 3:

Use e.which instead of e.charCode as well.

Post a Comment for "Limiting Input To Specified Regexp With Uppercase Chars In Ie"