prevent Duplicate values using Jquery Validation

前端 未结 11 1874
深忆病人
深忆病人 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 22:43

    Define a function that returns a boolean after making assertion on the validity of the value:

    const isValidGuid = (value) => {
      const validGuid = /^({|()?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}(}|))?$/;
      const emptyGuid = /^({|()?0{8}-(0{4}-){3}0{12}(}|))?$/;
      return validGuid.test(value) && !emptyGuid.test(value);
    };
    

    Use $.validator.addMethod to enable running of the function upon adding the same class name to an element

    $.validator.addMethod("isValidGuid", (value) => isValidGuid(value), "Please select a valid and non empty Guid value.");
    

    Use the class name on your desired element:

    <select id="title" class="isValidGuid" title="Please select a title!">
      <option value="00000000-0000-0000-0000-000000000000" selected="selected">(select)</option>
      <option value="33a1eb15-cdbc-4c85-be01-dcb4f393c0a5">Engineer</option>
      <option value="43b5d0f7-4915-41f1-b3b9-d6335299cc22">Physicist</option>
      <option value="d80322f2-bb76-447c-a6ac-77f145bac70d">Technician</option>
    </select> 
    
    0 讨论(0)
  • 2020-12-04 22:51
     <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');
                }
            });
        }
    
    0 讨论(0)
  • 2020-12-04 22:56

    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.

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

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


    Works with jQuery.Validate v1.13.1 or higher.

    0 讨论(0)
  • 2020-12-04 22:56

    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 equalTo validator. 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 addMethod function like so swapping the === 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'
      }
    
    0 讨论(0)
  • 2020-12-04 22:57

    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!):

    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/

    0 讨论(0)
  • 2020-12-04 22:58

    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").each(function() {
            if($(this).val() == $val)
                $repeat++;
        });
        if($repeat <= 1)
            return;
        alert("Repetido!");
        e.addClass("ui-state-error");
    }
    /////////////////////////////////
    $("input","div").blur(function(){
        ISeeWhatYouDidThere(
            $(this)
        );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="validDiv01">
        <input />
        <input />
        <input />
    </div>
    <hr />
    <div id="validDiv02">
        <input />
        <input />
        <input />
    </div>
    <hr />
    <div id="validDiv03">
        <input />
        <input />
        <input />
    </div>

    follow this for validate unique input value using jquery

    0 讨论(0)
提交回复
热议问题