[英]HTML5 custom validation for passwords
輸入2個不匹配的密碼時,我想創建一個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/小提琴中的密碼要求:6個字符,至少一個數字
jQuery get()
返回每個元素的dom元素...它們永遠不能相等
您要比較值。
嘗試改變
if (pwd1 != pwd2) { //compare 2 dom nodes
至
if ( pwd1.value != pwd2.value) { //compare 2 dom node values
但是請注意,由於您已超出有效期,因此您現在還需要考慮空值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.