使用Jquery验证防止重复值

Vic*_*cky 27 jquery

我有使用JSP动态生成的表单和表单文本字段.我正在使用Jquery验证,但希望添加functionlaty以防止表单中的重复输入.

例如

<form name="myForm" id="myForm">
      <input type="text" name="text1" id="text1">
      <input type="text" name="text2" id="text2">
      <input type="text" name="text3" id="text3">
      =
      = 
      N number of form fields
      <input type="text" name="textn" id="textn">

</form>
Run Code Online (Sandbox Code Playgroud)

我想检查是否使用jQuery验证在文本字段中输入了任何重复值.

小智 29

我对jquery验证很新,但我有一个类似的问题需要解决,我提出了以下解决方案(使用以前的答案获取灵感!):

使用Javascript:

jQuery.validator.addMethod("unique", function(value, element, params) {
    var prefix = params;
    var selector = jQuery.validator.format("[name!='{0}'][unique='{1}']", element.name, prefix);
    var matches = new Array();
    $(selector).each(function(index, item) {
        if (value == $(item).val()) {
            matches.push(item);
        }
    });

    return matches.length == 0;
}, "Value is not unique.");

jQuery.validator.classRuleSettings.unique = {
    unique: true
};
Run Code Online (Sandbox Code Playgroud)

用法:

<input name="currency1" unique="currency" />
<input name="currency2" unique="currency" />
Run Code Online (Sandbox Code Playgroud)

在这里演示:http://jsfiddle.net/mysteryh/bgzBY/


Ali*_*deh 12

Bug Magnet你的答案不是扩展jquery验证的功能.它是一个单独的脚本.

您可以通过在In jquery.validate.js中进行这些更改来实现此目的:

第275行:为唯一方法添加消息

messages: {
        unique: "This answer can not be repeated.",
Run Code Online (Sandbox Code Playgroud)

第744行:为unique添加新的类规则

classRuleSettings: {
        unique: { unique: true },
Run Code Online (Sandbox Code Playgroud)

最后一行899:添加新的唯一方法

methods: {

        unique: function (value, element) {
            var parentForm = $(element).closest('form');
            var timeRepeated = 0;
            $(parentForm.find('input:type=text')).each(function () {
                if ($(this).val() === value) {
                    timeRepeated++;
                }
            });
            if (timeRepeated === 1 || timeRepeated === 0) {
                return true
            }
            else { 
                return false
            }
        },
Run Code Online (Sandbox Code Playgroud)

现在,只需在调用验证函数时,就可以使用如下的独特方法:

$("#signupForm").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            unique: true,
            minlength: 2
        },
Run Code Online (Sandbox Code Playgroud)

  • 请使用`$ .validator.addMethod`而不是黑客插件. (8认同)

Bug*_*net 11

这样的事情应该有效:

$(function(){

$('input[name^="text"]').change(function() {

    var $current = $(this);

    $('input[name^="text"]').each(function() {
        if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id'))
        {
            alert('duplicate found!');
        }

    });
  });
});
Run Code Online (Sandbox Code Playgroud)

简而言之,这是如何工作的:每当用户在文本框中输入内容时,JQuery循环遍历表单中的所有文本框,并将其值与用户刚刚输入的值进行比较,如果找到重复值,则提醒用户.


FiS*_*ICS 6

对于这篇文章的新观众而言,这是值得的...我似乎无法让这些解决方案适合我(我正在使用v1.13.1)...所以我做了一点Frankensteining和拼凑的比特和从几个答案一起创建我需要的东西(并反过来为这个问题创建另一个答案).我的场景类似于@Vicky,因为我需要字段都是唯一的.但是,如果该字段不是必填字段,那么它可以为空.

使用@XGreen的部分解决方案,以及@Stephen Bugs Kamenar的建议,这是我提出的解决方案:

$.validator.addMethod("unique", function(value, element) {
    var parentForm = $(element).closest('form');
    var timeRepeated = 0;
    if (value != '') {
        $(parentForm.find(':text')).each(function () {
            if ($(this).val() === value) {
                timeRepeated++;
            }
        });
    }
    return timeRepeated === 1 || timeRepeated === 0;

}, "* Duplicate");
Run Code Online (Sandbox Code Playgroud)


如何使用

要使用此解决方案,您需要做的就是将值为unique添加到您想要唯一的输入字段中:

<input type="text" class="unique" name="firstName" />
<input type="text" class="unique" name="lastName" />
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,如果firstName和lastName的值相同,则jQuery Validate将抛出错误.


适用于jQuery.Validate v1.13.1或更高版本.