键入时检查密码匹配 [英] Checking password match while typing

查看:135
本文介绍了键入时检查密码匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有密码和确认密码输入字段的注册表。我想检查确认密码是否与用户输入密码时的密码匹配并给出相应的消息。所以我试着这样做:

I have a registration form with "password" and "confirm password" input fields. I want to check if the "confirm password" matches the "password" while the user is typing it and give the appropriate message. So I tried to do this:

这是HTML:

<div class="td">
    <input type="password" id="txtNewPassword" />
</div>
<div class="td">
    <input type="password" id="txtConfirmPassword" onChange="checkPasswordMatch();" />
</div>
    <div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>

这是checkPasswordMatch()函数:

And this is the checkPasswordMatch() function:

function checkPasswordMatch() {
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();

    if (password != confirmPassword)
        $("#divCheckPasswordMatch").html("Passwords do not match!");
    else
        $("#divCheckPasswordMatch").html("Passwords match.");
}

仅在用户离开时才会在输入时验证。

That didn't validate while typing, only when user leaves the field.

我试图使用onKeyUp而不是onChange - 也没有用。

I tried to use onKeyUp instead of onChange - also didn't work.

那怎么办呢?

谢谢!

推荐答案

onChange中的语法可能无效事件,我避免像这样使用(在html中),因为我觉得它很混乱,并且很难在最好的时候保持JavaScript整洁。

Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times.

我宁愿在javascript中的文档就绪事件上注册该事件。如果您想要在用户输入时进行验证,您也肯定也想使用keyup事件:

I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:

$(document).ready(function () {
   $("#txtConfirmPassword").keyup(checkPasswordMatch);
});

这是一个工作示例

我个人更愿意在密码字段更改时进行检查,这样,如果他们重新输入原始密码,那么你仍然会得到相同的验证检查:

Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:

$(document).ready(function () {
   $("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});

这是一个工作示例

这篇关于键入时检查密码匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆