javascript - 如何创建html5自定义验证?

标签 javascript html 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>

or in jsfiddle

如何为默认验证之类的工作创建自定义验证?

最佳答案

那么您可以使用 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/

相关文章:

javascript - 使用 ajax、php 和 javascript 验证通过后插入到数据库

javascript - 检测掉落的目标容器

javascript - 获取移动设备上的视口(viewport)大小

jquery - 使我的菜单适应响应式菜单

javascript - 如何从 get 中删除这个 ?url=

php - 如何在 Symfony 中自定义 bootstrap 水平表单主题/模板?

javascript - Vue.js 组件中的渲染组件

javascript - 无法使用clearInterval

javascript - 在 React 中设置单选按钮值

php - 通过 HTML 表单覆盖 MySQL 值