简体   繁体   English

密码的HTML5自定义验证

[英]HTML5 custom validation for passwords

I'm looking to create an HTML5 custom validation message when I enter 2 passwords which don't match. 输入2个不匹配的密码时,我想创建一个HTML5自定义验证消息。

Here's my HTML and JQuery 这是我的HTML和JQuery

HTML: HTML:

<form class="form-group main-settings-form" id="main-settings-form-password">

    <input class="form-control main-settings-form-input password-main" type="password" placeholder="Enter new password" id="new-password" pattern='(?=.*\d)(.{6,})' required>

    <input class="form-control main-settings-form-input" type="password" placeholder="Retype new password" id="confirm-password" pattern='(?=.*\d)(.{6,})' required>

    <div class="main-settings-form-buttons">
        <button type="button" class="btn btn-danger settings-edit-cancel">Cancel</button>
        <button class="btn btn-success" type="submit">Save</button>
        <br>
        <br>
        <a href="#"> Forgot password? </a>

    </div>

</form>

JS: JS:

$(document).ready(function () { //This confirms if the 2 passwords match

    $('#confirm-password').on('keyup', function (e) {

        var pwd1 = $("#new-password").get(0);
        var pwd2 = $("#confirm-password").get(0);
         pwd2.setCustomValidity("");

        if (pwd1 != pwd2) {
            document.getElementById("confirm-password").setCustomValidity("The passwords don't match"); //The document.getElementById("cnfrm-pw") selects the id, not the value
        }

        else {
            document.getElementById("confirm-password").setCustomValidity("");
            //empty string means no validation error
        }
        e.preventDefault();  //would still work if this wasn't present


});

});

The problem is, the message is always triggered even if the passwords do match. 问题是,即使密码确实匹配,也会始终触发该消息。 Please help me trigger the message only when the passwords dont match, and be allowed to safely submit when they do. 请仅在密码不匹配时帮助我触发消息,并在密码不匹配时安全提交。

JS fiddle: https://jsfiddle.net/kesh92/a8y9nkqa/ password requirements in the fiddle: 6 characters with atleast one number JS小提琴: https ://jsfiddle.net/kesh92/a8y9nkqa/小提琴中的密码要求:6个字符,至少一个数字

jQuery get() returns the dom elements of each...they can never be equal jQuery get()返回每个元素的dom元素...它们永远不能相等

You want to compare values. 您要比较值。

Try changing 尝试改变

if (pwd1 != pwd2) { //compare 2 dom nodes

To

if ( pwd1.value != pwd2.value) { //compare 2 dom node values

Note however that you also need to now consider empty values since you are over riding validty 但是请注意,由于您已超出有效期,因此您现在还需要考虑空值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM