仅在第一个字段上进行Jquery验证

问题描述 投票:1回答:2

我正在使用jQuery验证,并且正在动态显示字段。我必须设置动态字段的验证。

[我在做什么,我有一个记录列表,当管理员单击Add按钮时,模型将打开,然后管理员可以填写详细信息。我的验证仅适用于第一个字段。

您能帮我解决这个问题吗?

我正在使用下面的代码。

var isReqInprogress = false;
$(document).on('click', '.addexternal', function() {
  var user_id = $(this).attr("data-id");
  $('#myModal').modal('show');

  $("#register").validate({
    ignore: [],
    rules: {
      "fullname[]": {
        required: true
      },
      "dev[]": {
        required: true
      },
      "details[]": {
        required: {
          depends: function() {
            if (($('.dev').val() == "3")) {
              return true;
            } else {
              return false;
            }

          }
        }
      }

    },
    errorPlacement: function(error, element) {
      if (element.is("select")) {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }

    },
    submitHandler: function(form) {
      //form.submit();
      if (isReqInprogress) {
        return;
      }
      isReqInprogress = true;

      $.ajax({
        url: "process.php",
        type: "POST",
        dataType: "json",
        data: $('#register').serialize(), //i'll add user_id after some time

        success: function(data) {
          if (data.error == "true") {
            alert("added");
          } else {
            alert("error");
          }

          isReqInprogress = false;
        },
      }); // AJAX Get Jquery statment
    }

  });
});


/*duplicate form fields*/
$(document).ready(function() {
  var maxField = 10; //Input fields increment limitation
  var x = 1; //Initial field counter is 1
  var count = 2;
  //Once add button is clicked
  $(document).on('click', '#clicktoadd', function() {
    //alert("hello");        
    //Check maximum number of input fields
    if (x < maxField) {
      x++; //Increment field counter
      $(".modal-body").append('<div class="row"> <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <input type="text" name="fullname[]" class="form-control" placeholder="fullname"> </div></div><div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <select name="dev[]" class="form-control dev"> <option disabled="" selected="">Choose</option> <option value="1">Demo1</option> <option value="2">Demo2</option> <option value="3">Demo3</option> </select> </div></div><div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <input type="text" name="details[]" class="form-control"> </div></div></div><a href="javascript:void(0)" class="remove_button">Remove</a></div>');
    }
    count++;
  });
  //Once remove button is clicked
  $('.modal-body').on('click', '.remove_button', function(e) {
    e.preventDefault();
    $(this).parent('div').remove(); //Remove field html
    x--; //Decrement field counter
  });

});
.modal-dialog {
  max-width: 90% !important;
}

.new_add_bank {
  position: absolute;
  top: -50px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<table class="table table-striped table-bordered" style="width:100%">
  <thead>
    <tr>
      <th>id</th>
      <th>fullname</th>
      <th>Dev</th>
      <th>details</th>
      <th>action</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Demo</td>
      <td>Demo1</td>
      <td>dgdfg</td>
      <td><a href="javascript:void(0)" class="addexternal btn btn-primary" data-id="101">Add</a></td>
    </tr>
    <tr>
      <td>2</td>
      <td>xzxc</td>
      <td>Demo2</td>
      <td>mnbvg</td>
      <td><a href="javascript:void(0)" class="addexternal btn btn-primary" data-id="102">Add</a></td>
    </tr>
  </tbody>
</table>

<!-- The Modal -->
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Popup hading</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div id="clicktoadd"><a href="javascript:void(0);" class="btn btn-bg">Add More</a></div>
      <form method="post" action="#" name="register" id="register">
        <!-- Modal body -->
        <div class="modal-body">
          <div class="row">
            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <input type="text" name="fullname[]" class="form-control" placeholder="fullname">
              </div>
            </div>

            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <select name="dev[]" class="form-control dev">
                  <option disabled="" selected="">Choose</option>
                  <option value="1">Demo1</option>
                  <option value="2">Demo2</option>
                  <option value="3">Demo3</option>
                </select>
              </div>
            </div>

            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <input type="text" name="details[]" class="form-control">
              </div>
            </div>
          </div>
        </div>
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger">Submit</button>
        </div>
      </form>

    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
javascript jquery html bootstrap-4 jquery-validate
2个回答
0
投票

@@ questionbank jquery validate期望名称为唯一。您可以通过更改jquery.validate.js中的一段代码来覆盖它]

替换功能:

checkForm: function() {
  this.prepareForm();
  for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
    this.check( elements[ i ] );
  }
  return this.valid();
},

通过以下代码

checkForm: function() {
  this.prepareForm();
  for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
    if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
      for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
        this.check( this.findByName( elements[i].name )[cnt] );
      }
    } else {
      this.check( elements[i] );
    }
  }
  return this.valid();
},

它适用于数组输入。

[Look here

] >>

您可以通过在<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>行之后添加以下代码来覆盖插件方法>

<script type="text/javascript">    
    $.validator.prototype.checkForm = function() {
          this.prepareForm();
          for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
            if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
              for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
                this.check( this.findByName( elements[i].name )[cnt] );
              }
            } else {
              this.check( elements[i] );
            }
          }
          return this.valid();
    };

    $.validator.prototype.errorsFor = function (element) {
         var name = this.idOrName(element);
         var elementParent = element.parentElement;
         return this.errors().filter(function() {
           return $(this).attr('for') == name && $(this).parent().is(elementParent);
         });
    }
</script>
 

这在我测试时有效:

var isReqInprogress = false;
$(document).on('click', '.addexternal', function() {
  var user_id = $(this).attr("data-id");
  $('#myModal').modal('show');

  $("#register").validate({
    ignore: [],
    rules: {
      "dev[]": "required",
  "fullname[]": "required",
  "details[]": {
    required: {
      depends: function() {
        if (($('.dev').val() == "3")) {
          return true;
        } else {
          return false;
        }

      }
    }
  
  }
},
    errorPlacement: function(error, element) {
      if (element.is("select")) {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }

    },
    submitHandler: function(form) {
      //form.submit();
                $('input.validationAdd').each(function() {
                $("#register").rules("add", 
                    {
                        required: true
                    })
            });            
      if (isReqInprogress) {
        return;
      }
      isReqInprogress = true;

      $.ajax({
        url: "process.php",
        type: "POST",
        dataType: "json",
        data: $('#register').serialize(), //i'll add user_id after some time

        success: function(data) {
          if (data.error == "true") {
            alert("added");
          } else {
            alert("error");
          }

          isReqInprogress = false;
        },
      }); // AJAX Get Jquery statment
    }

  });
});


/*duplicate form fields*/
$(document).ready(function() {
  var maxField = 10; //Input fields increment limitation
  var x = 1; //Initial field counter is 1
  var count = 2;
  //Once add button is clicked
  $(document).on('click', '#clicktoadd', function() {
    //alert("hello");        
    //Check maximum number of input fields
    if (x < maxField) {
      x++; //Increment field counter
      $(".modal-body").append($('<div class="row"> <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <input type="text" name="fullname'+x+'[]" class="form-control validationAdd" placeholder="fullname"> </div></div><div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <select name="dev[]" class="form-control dev"> <option disabled="" selected="">Choose</option> <option value="1">Demo1</option> <option value="2">Demo2</option> <option value="3">Demo3</option> </select> </div></div><div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="form-group"> <input type="text" name="details[]" class="form-control"> </div></div></div><a href="javascript:void(0)" class="remove_button">Remove</a></div>'));
    }
    count++;
  });
  //Once remove button is clicked
  $('.modal-body').on('click', '.remove_button', function(e) {
    e.preventDefault();
    $(this).parent('div').remove(); //Remove field html
    x--; //Decrement field counter
  });

});
.modal-dialog {
  max-width: 90% !important;
}

.new_add_bank {
  position: absolute;
  top: -50px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<table class="table table-striped table-bordered" style="width:100%">
  <thead>
    <tr>
      <th>id</th>
      <th>fullname</th>
      <th>Dev</th>
      <th>details</th>
      <th>action</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Demo</td>
      <td>Demo1</td>
      <td>dgdfg</td>
      <td><a href="javascript:void(0)" class="addexternal btn btn-primary" data-id="101">Add</a></td>
    </tr>
    <tr>
      <td>2</td>
      <td>xzxc</td>
      <td>Demo2</td>
      <td>mnbvg</td>
      <td><a href="javascript:void(0)" class="addexternal btn btn-primary" data-id="102">Add</a></td>
    </tr>
  </tbody>
</table>

<!-- The Modal -->
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Popup hading</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div id="clicktoadd"><a href="javascript:void(0);" class="btn btn-bg">Add More</a></div>
      <form method="post" action="#" name="register" id="register">
        <!-- Modal body -->
        <div class="modal-body">
          <div class="row">
            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <input type="text" name="fullname[]" class="form-control" placeholder="fullname">
              </div>
            </div>

            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <select name="dev[]" class="form-control dev">
                  <option disabled="" selected="">Choose</option>
                  <option value="1">Demo1</option>
                  <option value="2">Demo2</option>
                  <option value="3">Demo3</option>
                </select>
              </div>
            </div>

            <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12">
              <div class="form-group">
                <input type="text" name="details[]" class="form-control">
              </div>
            </div>
          </div>
        </div>
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger">Submit</button>
        </div>
      </form>

    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>

官方doc


0
投票

这在我测试时有效:

© www.soinside.com 2019 - 2024. All rights reserved.