如何处理两个javascript事件?

时间:2011-05-18 18:15:30

标签: javascript html validation

我正在尝试对表单的密码字段进行一些验证检查。我正在调用函数onkeypress来检查capsLock是打开还是关闭,然后onblur函数检查密码字段值。但是当我在密码字段中输入任何值时,onblur会立即与onkeypress一起运行。这违背了检查大写锁定然后是字段值的目的。

HTML:

<input type="password" size=50 name="password" value="" onkeypress="checkCapsLock(event);" onblur="chkPsw(this.value);">

JavaScript的:

function chkPsw(inpsw){
    var psw = inpsw.toLowerCase(inpsw);
    psw = trim(psw);
    if (psw.length<4 || psw.length>15){
        alert ('password length can be min. 4 and max. 15 chars' );
        return false;
    }
    var p1=/^[a-z0-9_\-\!\@\$\%\&\(\)\{\}\[\]\<\>]+$/;/* a-z 0-9 _ - ! @ $ % & ( ) { } [ ] < > */
    if(p1.test(psw)) {
        alert("The password:::: "+psw+" :::: is ok.");
        return true;
    } else {
        var p2 = /\s+/;
        if (p2.test(psw)){
            alert(psw+" is not ok. Space is not allowed.");
            return false;
        } else{
            alert(psw+"\n is not ok only a-z 0-9 _ - ! @ $ % & ( ) { } [ ] < > ");
            return false;
        }
    }
}


function checkCapsLock( e ) {
    var myKeyCode=0;
    var myShiftKey=false;
    var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

    // Internet Explorer 4+
    if ( document.all ) {
        myKeyCode=e.keyCode;
        myShiftKey=e.shiftKey;
    }

    if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
        alert( myMsg );
        return false;
    } else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
        alert( myMsg );
        return false;
    } else {
        return true;
    }
}

我想我已经说清楚了。如果任何人可以帮助我那将是伟大的。

我想要的是当有人开始输入此密码字段时,会检查capsLock的状态并告知用户,然后当填写完整字段并且用户移动到下一个字段时,将检查密码值。 / p>

1 个答案:

答案 0 :(得分:0)

嗯,问题是你正在使用警告框来通知用户(不良做法和烦人)导致密码字段失去焦点。

解决方案?使用布尔条件

这是一个jQuery示例(我正在清理你的代码),

jsFiddle:http://jsfiddle.net/MnMps/

jQuery.fn.caps = function(cb){
    return this.keypress(function(e){
        var w = e.which ? e.which : (e.keyCode ? e.keyCode : -1);
        var s = e.shiftKey ? e.shiftKey : (e.modifiers ? !!(e.modifiers & 4) : false);
        var c = ((w >= 65 && w <= 90) && !s) || ((w >= 97 && w <= 122) && s);
        cb.call(this, c);
    });
};

var alerting = false;

$('#password').caps(function(caps){
    if(caps){
        alerting = true;
        alert('Unintentional uppercase leads to wars!');
       }
});

$('#password').blur(function() {
    if(alerting == false && !this.value.match(/^[a-z0-9_\-\!\@\$\%\&\(\)\{\}\[\]\<\>]+$/)) {
        alert("Abort! Invalid character detected!");
    }
    alerting = false;
});

PS:支持封锁检测的道具,http://plugins.jquery.com/plugin-tags/caps-lock

编辑:放弃清理代码。