2016-10-03 52 views
0

我在输入2个不匹配的密码时正在创建HTML5自定义验证消息。HTML5自定义密码验证

这里是我的HTML和JQuery

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:

$(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 


}); 

}); 

的问题是,总是触发消息,即使密码比赛。只有在密码不匹配的情况下,才能帮助我触发信息,并且可以在他们这样做时安全地提交。

JS小提琴:在小提琴https://jsfiddle.net/kesh92/a8y9nkqa/ 密码要求:用于至少一个数量

+1

您应该使用'.VAL() '而不是'.get(0)'来获得密码字段的值。 – Terry

回答

1

的jQuery get()返回各自的DOM元素6个角色......他们永远不可能等于

要比较值。

尝试改变但是

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

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

请注意,您还需要现在考虑空值,因为你是在骑validty

+0

这个完美的作品!万分感谢!我有一个后续问题。如果我将原始代码更改为'var pwd1 = $(“#new-password”)value;'和'var pwd2 = $(“#confirm-password”).value;'并保持其他所有内容相同,shouldn它工作吗?因为它不,所以只是好奇为什么。谢谢! –

+0

2个原因...您正试图管理这些元素的'validity'属性,并且'$().value'不是jQuery属性.... jQuery使用'val()'。建议你不要混用jquery和dom原生方法。它会让你困惑 – charlietfl

+0

太棒了,谢谢你:) –