我在输入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/ 密码要求:用于至少一个数量
您应该使用'.VAL() '而不是'.get(0)'来获得密码字段的值。 – Terry