如何创建 html5 自定义验证?

Lai*_*290 4 html javascript forms validation customization

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

或在 jsfiddle

如何为默认验证等工作创建自定义验证?

rye*_*lar 10

好吧,您可以使用 JQuery 并附加一个要为密码选择的属性,以通过input事件相互验证。使用 setCustomValidity() 设置受影响的输入的消息以在提交表单时覆盖默认消息。

请参阅更新的小提琴

正如您在小提琴中看到的,您所要做的就是添加一个属性,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>
Run Code Online (Sandbox Code Playgroud)

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('');
});
Run Code Online (Sandbox Code Playgroud)