gpt4 book ai didi

jQuery 验证多个不相等的输入

转载 作者:行者123 更新时间:2023-12-03 22:57:43 26 4
gpt4 key购买 nike

我已经成功地在我的表单上设置了 jQuery 验证插件,并且我为两个字段给出了规则,其中它们的值不应匹配。具体来说,email 和 email_2 输入现在不能相同,但这是可行的。但我真正需要的是以相同的方式验证多个输入(在本例中为 4 个输入)。我有 email、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,
notequal: 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,
notEqualToGroup: ['.distinctemails']
},
email_3: {
required: true,
notEqualToGroup: ['.distinctemails']
},
email_4: {
required: true,
notEqualToGroup: ['.distinctemails']
},
},
});

关于jQuery 验证多个不相等的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com