36

我有两个输入,例如

pass:       <input type="password" name="pass" required/>
pass again:  <input type="password" name="pass2" required/>

我想比较这些输入,如果它们匹配,则将输入设置为有效。我试过这个,但我认为这prop('valid', true);不起作用:

$(document).ready(function() {
    $('input[name=pass2]').keyup(function() {
        if($('input[name=pass]').val() == $('input[name=pass2]').val()) {
            $('#pass_hint').empty();
            $('#pass_hint').html('match');
            $(this).prop('valid', true);
        } else {
            $('#pass_hint').empty();
            $('#pass_hint').html('mismatch');
            $(this).prop('invalid', true);
        }
    });
});

我创建了一个注册表单,如果密码不同,则输入字段无效,我无法提交并显示一些提示。...而且我不知道如何将此输入设置为无效

4

1 回答 1

46

HTMLInputElement 接口中,没有validor之类的属性invalid

您可以将该setCustomValidity(error)方法与本机表单验证一起使用。

至于您的脚本,这里有一个可以在所有兼容 HTML5 的浏览器中运行的演示:

$('input[name=pass2]').keyup(function () {
    'use strict';

    if ($('input[name=pass]').val() === $(this).val()) {
        $('#pass_hint').html('match');
        this.setCustomValidity('');
    } else {
        $('#pass_hint').html('mismatch');
        this.setCustomValidity('Passwords must match');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='#'>
    <p>Password:
        <input name=pass type=password required>
    </p>
    <p>Verify:
        <input name=pass2 type=password required>
    </p>
    <p id=pass_hint></p>
    <button type=submit>Submit</button>
</form>

于 2013-08-08T14:58:22.663 回答