Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating '%' and '(' on JavaScript

Greetings all. I have the following function to validate input depending if 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 its an easy function to understand.

The problem is the following. The keycode for '%' is 37 the same than the left arrow and the keycode for '(' is 40 the same than the right arrow. So my function is not validating '%' and '(' and it sucks. I dont know what to do, please help.

like image 756
daniel Avatar asked Nov 13 '22 23:11

daniel


1 Answers

The keypress event doesn't fire for arrow and delete keys, so you can just remove your if statement. Darn you FireFox!

You are mixing up keyCode and charCode, which is understandable because event.keyCode actually contains charCode for keyPress events, unlike keydown and keyup. The keyCode for ( is 57 (same as for 9 - those characters are on the same key). Its charCode is 40. Arrow keys don't have charCodes, so they don't fire keypress events. (Except in FireFox... Argh!)

Your best bet is to use the keydown event and look for keyCode rather than charCode, checking for shift keys when necessary. You'll have to manually map keyCodes to characters when the shift key is pressed.

like image 166
gilly3 Avatar answered Jan 09 '23 17:01

gilly3