开发者

Validating '%' and '(' on JavaScript

开发者 https://www.devze.com 2023-03-05 23:40 出处:网络
Greetings all. I have the following function to validate input depending if is numeric, alpha, alphanumeric and email:

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 no开发者_如何学Pythont validating '%' and '(' and it sucks. I dont know what to do, please help.


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.


Slightly OT (apologies) but you may want to look at one of the Javascript libraries out there, for example JQuery; almost all of them come with (or have) libraries for "validating input".

For example: if you were using JQuery you may consider the "Validation" plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/


Check for whether the shift key is being pressed as well by checking 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 handle the keydown event instead of the keypress event, which won't result in overlapping key codes.

0

精彩评论

暂无评论...
验证码 换一张
取 消