Checking "%" and "(" in JavaScript

Welcome all. I have the following function to check input depending if it is numeric, alpha, alphanumeric and email:

  function permite(e, permitidos) {

    var key = e.keyCode || e.which;

    //Validate if its an arrow or delete button
    if((key == 46) || (key == 8) || (key >= 37 && key <= 40))
        return true;

    var keychar = String.fromCharCode(key);

    switch(permitidos) {
        case 'num':
            permitidos = /^[0-9]$/;
            break;
        case 'car':
            permitidos = /^[\sa-zA-Z]$/;
            break;
        case 'num_car':
            permitidos = /^[\sa-zA-Z0-9]$/;
            break;
        case 'correo':
            permitidos = /^[a-zA-Z0-9._\-+@]$/;
            break;
    }

    return permitidos.test(keychar);


 }

The var names are in Spanish, but they are easy to understand.

The problem is as follows. The key code for "%" is 37 than the left arrow, and the key code for "(" 40 "is the same as the right arrow. Therefore, my function does not check"% "and" ("and this sucks". I do not know what to do, please help.

+5
source share
3 answers

keypress , if. Darn your FireFox!

keyCode charCode, , event.keyCode charCode keypress , keydown keyup. KeyCode ( 57 ( , 9 - ). charCode 40. charCodes, keypress. ( FireFox... Argh!)

keydown keyCode, charCode, . keyCodes shift.

+1

OT (), Javascript, JQuery; ( ) " ".

: JQuery, "Validation" - http://bassistance.de/jquery-plugins/jquery-plugin-validation/

0

Check if the shift key is pressed as well as event.shiftKey :

//Validate if its an arrow or delete button
if((key == 46) || (key == 8) || (key >= 37 && key <= 40 && !e.shiftKey))
    return true;

Another option (depending on your application) is to process the event keydowninstead of the event keypress, which will not lead to overlapping key codes.

0
source

All Articles