jQuery验证多个不相等的输入

前端之家收集整理的这篇文章主要介绍了jQuery验证多个不相等的输入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经设法在我的表单上设置了jQuery validate插件,并为两个字段提供了规则,其中的值不应该匹配.具体来说,电子邮件和email_2输入现在不能相同,这是有效的.但我真正需要的是以相同的方式验证多个输入(在这种情况下为4个).我有电子邮件,email_2,email_3,email_4,但这些都不应该是平等的.你可以在我的 jsfiddle here中看到它,如果你有解决方案,你可以更新它并把它放回答案中:

HTML:

<form id="signupform" method="post">
<input id="email" name="username" />
<br/ >
<input id="email_2" name="email_2" />
<br />
<input id="email_3" name="email_3" />
<br />
<input id="email_4" name="email_4" />
<br />
<input id="submit" type="submit" value="submit" />   
</form>

jQuery的:

$.validator.addMethod("notequal",function(value,element) {
 return $('#email').val() != $('#email_2').val()},"* You've entered this one already");

// validate form    
$("#signupform").validate({

rules: {
    email: {
        required: true,notequal: true
    },email_2: {
        required: true,},});

验证所有输入的最佳解决方案是什么?

解决方法

是的,它仍适用于1.10.1

DEMO

来源:http://www.anujgakhar.com/2010/05/24/jquery-validator-plugin-and-notequalto-rule-with-multiple-fields/

HTML

<form id="signupform" method="post">
    <p>
        <input class="distinctemails" id="email" name="username" /></p>
    <p>
        <input class="distinctemails" id="email_2" name="email_2" /></p>
    <p>
        <input class="distinctemails" id="email_3" name="email_3" /></p>
    <p>
        <input class="distinctemails" id="email_4" name="email_4" /></p>
    <p>
        <input id="submit" type="submit" value="submit" />
    </p>
</form>

jQuery的

jQuery.validator.addMethod("notEqualToGroup",function (value,element,options) {
    // get all the elements passed here with the same class
    var elems = $(element).parents('form').find(options[0]);
    // the value of the current element
    var valueToCompare = value;
    // count
    var matchesFound = 0;
    // loop each element and compare its value with the current value
    // and increase the count every time we find one
    jQuery.each(elems,function () {
        thisVal = $(this).val();
        if (thisVal == valueToCompare) {
            matchesFound++;
        }
    });
    // count should be either 0 or 1 max
    if (this.optional(element) || matchesFound <= 1) {
        //elems.removeClass('error');
        return true;
    } else {
        //elems.addClass('error');
    }
},jQuery.format("Please enter a Unique Value."))

// validate form    
$("#signupform").validate({

    rules: {
        email: {
            required: true,notEqualToGroup: ['.distinctemails']
        },email_2: {
            required: true,email_3: {
            required: true,email_4: {
            required: true,});
原文链接:https://www.f2er.com/jquery/181506.html

猜你在找的jQuery相关文章