如何创建html5自定义验证? [英] How to create html5 custom validation?

查看:72
本文介绍了如何创建html5自定义验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用html 5表单验证在提交之前验证我的表单,如果有效,则提交,但是我需要验证我的用户注册表单,因此需要验证密码确认值是否等于密码,这是我的表单示例:

I am using html 5 form validation for validate my form before submit, if is valid, submit, but I need validate my User Register form, so it need validate if Password Confirm value is equal camp Password, below is my form example:

<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>

或在jsfiddle中

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

How to can I create my custom validation for work like default validations?

推荐答案

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

Well you can use JQuery and attach an attribute to be selected for the passwords to validate each other via input event. Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted.

请参阅更新的小提琴.

就像在小提琴中看到的那样,您要做的就是添加一个属性data-equal-id,其中该属性值必须是要测试的密码输入元素的ID.

As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.

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('');
});

这篇关于如何创建html5自定义验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆