prevent Duplicate values using Jquery Validation

前端 未结 11 1875
深忆病人
深忆病人 2020-12-04 22:28

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

相关标签:
11条回答
  • 2020-12-04 23:02

    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.

    0 讨论(0)
  • 2020-12-04 23:02

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

    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.

    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.

    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.messages property.

    0 讨论(0)
  • 2020-12-04 23:06

    This should work:

    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;
            }
           }
         }
      })
    
    })
    
    0 讨论(0)
  • 2020-12-04 23:09

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

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

    or maybe:

    $('.name').each(function () {
                if ($(this).val() === value) {
                    timeRepeated++;
                }
    
    0 讨论(0)
  • 2020-12-04 23:10

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

    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)
        );
    });
    
    0 讨论(0)
提交回复
热议问题