這是an extension of the the question我今天早些時候曾問過(它還沒有解決,任何幫助都非常感謝)。我在堆棧溢出中看到了很多關於這個問題,我的代碼是基於我在教程網站上找到的。密碼確認驗證沒有按預期顯示
我有2個密碼錶單,我想驗證。我只是想提交它,如果他們匹配。這裏是我的代碼 -
<li>
<div class="input-group col-xs-5 pw">
<input type="password" name="pw" class="form-control" placeholder="Enter a new password" id="new-pw" />
</div>
</li>
<li>
<div class="input-group col-xs-5">
<input type="password" name="cnfrm-pw" id="cnfrm-pw" class="form-control" placeholder="Confirm new password" />
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" id="pw-btn"> <em class="glyphicon glyphicon-circle-arrow-right"> </em> </button>
</span>
</div>
</li>
我的Javascript成爲
$(document).ready(function() {
$('#pw-btn').click(function() {
var pwd1 = document.getElementById("new-pw").value;
var pwd2 = document.getElementById("cnfrm-pw").value;
if (pwd1 != pwd2)
{
document.getElementById("cnfrm-pw").setCustomValidity("Passwords Don't Match");
}
else {
document.getElementById("cnfrm-pw").setCustomValidity('');
//empty string means no validation error
}
}
);
});
我期待的HTML5表單驗證,它告訴我密碼不匹配,一些like this。但是沒有任何反應 我的自定義驗證方法有錯嗎?提前謝謝各位,非常感謝您的幫助和建議。
ANSWER
我用下面的代碼得到這個工作。這是對提交答案的修改。感謝所有的幫助傢伙!
HTML:
<form action="#" id="f" method="post">
<li>
<div class="input-group col-xs-5 pw">
<input type="password" name="pw" class="form-control new-pw" placeholder="Enter a new password" id="new-pw" required pattern="(?=.*\d)(.{6,})" />
</div>
</li>
<li>
<div class="input-group col-xs-5">
<input type="password" name="cnfrm-pw" id="cnfrm-pw" class="form-control cnfrm-pw" required placeholder="Confirm new password" />
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" id="pw-btn"> </button>
</span>
</div>
</li>
</form>
JS
$(document).ready(function() { //This confirms if the 2 passwords match
$('#f').on('keyup', '.cnfrm-pw', function (e) {
var pwd1 = document.getElementById("new-pw").value;
var pwd2 = document.getElementById("cnfrm-pw").value;
if (pwd1 != pwd2) {
document.getElementById("cnfrm-pw").setCustomValidity("The passwords don't match"); //The document.getElementById("cnfrm-pw") selects the id, not the value
}
else {
document.getElementById("cnfrm-pw").setCustomValidity("");
//empty string means no validation error
}
e.preventDefault(); //would still work if this wasn't present
}
);
});
什麼是您所面臨的問題? – Praveen
@PraveenI對指定問題的問題進行了更新。謝謝 –