这是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对指定问题的问题进行了更新。谢谢 –