我在提交前使用 html 5 表单验证来验证我的表单,如果有效,则提交,但我需要验证我的用户注册表单,所以它需要验证密码确认值是否等于 camp 密码,下面是我的表单示例:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
如何为默认验证之类的工作创建自定义验证?
最佳答案
那么您可以使用 JQuery 并附加一个要为密码选择的属性,以通过 input
事件相互验证。使用 setCustomValidity() 设置受影响的输入的消息以在提交表单时覆盖默认消息。
查看更新的 fiddle .
正如您在 fiddle 中看到的,您所要做的就是添加一个属性data-equal-id
,其中属性值必须是要测试的密码输入元素的ID。
HTML
<h1>How to create html5 validation for password confirm?</h1>
<hr>
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf" data-equal-id="pass" /><br/>
<input type="submit"/>
</form>
Javascript
$('[data-equal-id]').bind('input', function() {
var to_confirm = $(this);
var to_equal = $('#' + to_confirm.data('equalId'));
if(to_confirm.val() != to_equal.val())
this.setCustomValidity('Password must be equal');
else
this.setCustomValidity('');
});
关于javascript - 如何创建html5自定义验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22702629/