使用 Jquery 验证防止重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2955536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:37:17  来源:igfitidea点击:

prevent Duplicate values using Jquery Validation

jquery

提问by Vicky

I have form and form text field which generates dynamically using JSP. And I'm using Jquery validation but want to add functionlaty to prevent duplicate entry in the form.

我有使用 JSP 动态生成的表单和表单文本字段。我正在使用 Jquery 验证,但想添加功能以防止表单中的重复条目。

E.g.

例如

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

I want to check if there is any duplicate value entered in the textfield using jQuery validation.

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

采纳答案by Bug Magnet

Something like this should work:

这样的事情应该工作:

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

    });
  });
});

In a nutshell, how this works is: Whenever a user enters something into a text box, JQuery loops through all the text boxes in the form and compares their values with the value that the user just entered, if a duplicate value is found, then alert the user.

简而言之,它的工作原理是:每当用户在文本框中输入内容时,JQuery 循环遍历表单中的所有文本框,并将它们的值与用户刚刚输入的值进行比较,如果发现重复值,则提醒用户。

回答by MysteryH

I'm pretty new to jquery validation, but I had a similar issue to solve, I came up with the following solution (using previous answers for inspiration!):

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

Javascript:

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

Usage:

用法:

<input name="currency1" unique="currency" />
<input name="currency2" unique="currency" />

Demo here: http://jsfiddle.net/mysteryh/bgzBY/

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

回答by Ali Habibzadeh

Bug Magnet your answer is not extending the functionality of jquery validate. its a separate script.

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

You can achieve this by making these changes in In jquery.validate.js:

您可以通过在 jquery.validate.js 中进行这些更改来实现这一点:

line 275: add a message for the unique method

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

messages: {
        unique: "This answer can not be repeated.",

line 744: add a new class rule for unique

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

classRuleSettings: {
        unique: { unique: true },

and finally line 899: add the new unique method

最后第 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
            }
        },

now simply when you call your validate function you can use a unique method like this:

现在,当您调用验证函数时,您可以使用这样的独特方法:

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

回答by FiSH GRAPHICS

For what it's worth to new viewers of this post... I couldn't seem to get any of these solutions to work for me (I'm using v1.13.1)... so I did a little Frankensteining and pieced bits and pieces from several answers together to create what I needed (and in turn creating another answer for this question). My scenario was similar to @Vicky in the since that I needed the fields to all be unique. However, if the field wasn't a required field, then it was okay for it to be empty.

对于这篇文章的新观众来说,它的价值是什么......我似乎无法让这些解决方案中的任何一个对我有用(我使用的是 v1.13.1)......所以我做了一些科学怪人并拼凑了一些东西将几个答案拼凑在一起来创建我需要的东西(并反过来为这个问题创建另一个答案)。我的场景类似于@Vicky,因为我需要所有字段都是唯一的。但是,如果该字段不是必填字段,则它可以为空。

Using part of the solution from @XGreen, and the suggestion from @Stephen Bugs Kamenar, this is the solution that I came up with:

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

Solution

解决方案

$.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");



How to Use

如何使用

To use this solution, all you need to do is add a classwith the value of, unique, to the input fields that you are wanting to be unique:

要使用此解决方案,所有你需要做的就是添加一个用,价值独特,在输入字段,你是想成为独一无二的:

<input type="text" class="unique" name="firstName" />
<input type="text" class="unique" name="lastName" />

In the example above, jQuery Validate will throw an error if the value of firstName and lastName are the same.

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


Works with jQuery.Validate v1.13.1 or higher.


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

回答by rladd

If I'm not mistaken, you could narrow the duplicate comparison down a bit. For example, I just want to look at other fields of the same class, say 'name':

如果我没记错的话,您可以缩小重复比较的范围。例如,我只想查看同一个类的其他字段,比如'name':

$(parentForm.find('.name')).each(function () {
            if ($(this).val() === value) {
                timeRepeated++;
            }

or maybe:

或者可能:

$('.name').each(function () {
            if ($(this).val() === value) {
                timeRepeated++;
            }

回答by VinayKumarHA

 <input type="text" id= "txtName" class="name" onfocusout="checkName(this)">
 function checkName(thisvalues) {
        var currentval = $('#' + thisvalues.id).val();
        $('.name').each(function () {
            console.log(this.value + ',' + this.id);
            if (currentval == this.value && thisvalues.id != this.id) {
                alert('With' + this.value+ 'name already exists');
            }
        });
    }

回答by Kyle

I know this is an old question and the answer is slightly off track from the original question but I was pulling my hair out for a while as I only wanted to check a specific field VS another specific field and could't get it to work any other way. The jQuery validation comes with an equalTovalidator. https://jqueryvalidation.org/equalTo-method/

我知道这是一个老问题,答案与原始问题略有出入,但我拉了一段时间的头发,因为我只想检查特定领域 VS 另一个特定领域,但无法使其正常工作另一种方式。jQuery 验证带有一个equalTo验证器。https://jqueryvalidation.org/equalTo-method/

Which in the source code looks like:

源代码中的内容如下:

equalTo: function( value, element, param ) {

        // Bind to the blur event of the target in order to revalidate whenever the target field is updated
        var target = $( param );
        if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) {
            target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() {
                $( element ).valid();
            } );
        }
        return value === target.val();
    }

take this code and use the addMethodfunction like so swapping the ===to !==:

使用此代码并使用addMethod像这样交换===to的函数!==

jQuery.validator.addMethod("notEqualTo", function(value, element, param) {
        // Bind to the blur event of the target in order to revalidate whenever the target field is updated
        var target = $( param );
        if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) {
            target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() {
                $( element ).valid();
            } );
        }
        return value !== target.val();
        // condition returns true or false
    }, "Values must be unique");

Then apply in rules section:

然后在规则部分应用:

 'first_name':{
      required: true,
      notEqualTo: '#last_name'
  }

回答by qJake

Here is another slightly modified answer from the previous answers.

这是先前答案的另一个稍微修改的答案。

This one checks duplicate values against form elements with the same name(which is perfectly valid from an HTML standpoint).

这个检查针对具有相同名称的表单元素的重复值(从 HTML 的角度来看这是完全有效的)。

For example:

例如:

<input type="email" name="emailField" id="email-1" />
<input type="email" name="emailField" id="email-2" />
<input type="email" name="emailField" id="email-3" />

Note: You don't even need the ID, it's just shown for completeness.

注意:您甚至不需要 ID,它只是为了完整性而显示。

The following custom validator will validate these inputs as having unique values:

以下自定义验证器将验证这些输入是否具有唯一值:

$.validator.addMethod('unique', (value, element) => {
    var timeRepeated = 0;
    if (value && value.length)
    {
        $(`input[name=${(element as HTMLFormElement).name}]`).each(function ()
        {
            if ($(this).val() === value)
            {
                timeRepeated++;
            }
        });
    }
    return timeRepeated === 1 || timeRepeated === 0;
});

Note: This is TypeScript, but easily convertible back to pure JS.

注意:这是 TypeScript,但很容易转换回纯 JS。

Be sure to enable the rule elsewhere, e.g.:

请务必在其他地方启用该规则,例如:

var myValidationRules = {
  emailField: {
    unique: true
  }
}

And put a validation message on the validator definition above, or use the validator.settings.messagesproperty.

并在上面的验证器定义上放置验证消息,或使用该validator.settings.messages属性。

回答by Absar Seevayi

This should work:

这应该有效:

HTML

HTML

<form name="myForm" id="myForm">
   <input type="text">
   <input type="text">
   <input type="text">
   <input type="text">
   <button>Click</button>
</form>

JQuery

查询

$(function(){

    $('button').click(function(){

    var len = $('input').length,i,k;
    $('input').css({'border':'solid 1px #888'})

    for(i=0; i < len; i++){
      var v = $('input:eq('+ i +')').val();
      for( k=0; k < i; k++ ){
        var s = $('input:eq('+ k +')').val();
        if( s == v ){
          $('input:eq('+ i +')').css({'border':'solid 1px #F00'})
          $('input:eq('+ k +')').css({'border':'solid 1px #F00'})
          return false;
        }
       }
     }
  })

})

回答by Dr. Hyde

I won't use the Validator plugin, but, maybe this http://jsfiddle.net/6dbrjbg6/2/can help:

我不会使用 Validator 插件,但是,也许这个http://jsfiddle.net/6dbrjbg6/2/可以帮助:

function ISeeWhatYouDidThere(e) {
    var $repeat = 0,
        $val = e.val(),
        $parent = "#" + e.closest("div").attr("id")
    ;
    if($.trim($val) == "")
        return;
    e.removeClass("ui-state-error");
    $("input", $parent).each(function() {
        if($(this).val() == $val)
            $repeat++;
    });
    if($repeat <= 1)
        return;
    alert("Repetido!");
    e.addClass("ui-state-error");
}
/////////////////////////////////
$("input","div").blur(function(){
    ISeeWhatYouDidThere(
        $(this)
    );
});