prevent Duplicate values using Jquery Validation

前端 未结 11 1902
深忆病人
深忆病人 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: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'
      }
    

提交回复
热议问题