如何在动态添加的表单字段上实施先前声明的 jquery.validate 规则

How to implement previously declared jquery.validate rules on dynamically added form fields

我必须克隆表单的特定部分并且必须实施之前定义的相同验证规则。

在我研究这个问题时,几乎所有的人都建议在新生成的元素中再次添加新规则。因此,我曾尝试使用以下代码添加新规则

let $contactItem = $(".contact")
        .first()
        .clone()
        .insertAfter($(".contact").last());
        $contactItem.find("input").each(function(){
        $(this).rules("add", {
     required : true,
     messages : { required : 'field is required.' }
  });
});

但是我运气不好,这个技巧并没有解决我的问题。所以我正在寻找另一种解决方案。

有关我正在使用的库的一些详细信息:

$(document).ready(function() {
  let $validator;
  $("#btnAddNew")
    .off("click")
    .on("click", function() {
     let $contactItem = $(".contact")
        .first()
        .clone()
        .insertAfter($(".contact").last());
    });
  $validator = $("#contactForm").validate({
    rules: {
      firstName: {
        required: true
      },
      lastName: {
        required: true
      }
    },
    messages: {
      firstName: {
        required: "* Required"
      },
      lastName: {
        required: "* Required"
      }
    },
    ignore: ":hidden, :disabled"
  });
  $("#btnSave")
    .off("click")
    .on("click", function() {
      if ($validator.form()) {
        console.log("ok");
      }
    });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>
<div class="container">
    <form id="contactForm">
    <div class="contact">
        <h5 class="card-title">Contact Info</h5>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label for="inputEmail4">First Name</label>
                <input type="text" class="form-control" name="firstName" placeholder="Your First Name">
          </div>
                <div class="form-group col-md-6">
                    <label for="inputEmail4">Last Name</label>
                    <input type="text" class="form-control" name="lastName" placeholder="Your Last Name">
    </div>
                </div>
    </div>
                <button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
                <button type="button" id="btnSave" class="btn btn-primary">Save</button>
    </form>
</div>

只需在元素中添加 required 可能是最简单的解决方案并修改默认消息。

我还评论了一种设置 class 规则的方法。

请注意,您还需要修改名称以使其唯一。我使用了非常简单的增量逻辑,修改是否要添加和删除

$.extend($.validator.messages, {
  required: "* required."
})

// Alternate using class rules
/*jQuery.validator.addClassRules("name-field", {
  required: true
});*/


$(document).ready(function() {
  let $validator;
  $("#btnAddNew")
    .off("click")
    .on("click", function() {
      let $contact = $(".contact");
      let $contactItem = $contact
        .first()
        .clone()
        .insertAfter($(".contact").last());
      // increment input names
      $contactItem.find('input').attr('name', function(_, curr) {
        return curr + $contact.length
      });
    });

  
  $validator = $("#contactForm").validate();


  $("#btnSave")
    .off("click")
    .on("click", function() {
      if ($validator.form()) {
        console.log("ok");
      }
    });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>
<div class="container">
  <form id="contactForm">
    <div class="contact">
      <h5 class="card-title">Contact Info</h5>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="inputEmail4">First Name</label>
          <input type="text" class="form-control name-field" name="firstName" placeholder="Your First Name" required>
        </div>
        <div class="form-group col-md-6">
          <label for="inputEmail4">Last Name</label>
          <input type="text" class="form-control name-field" name="lastName" placeholder="Your Last Name" required>
        </div>
      </div>
    </div>
    <button type="button" id="btnAddNew" class="btn btn-primary">Add Next</button>
    <button type="button" id="btnSave" class="btn btn-primary">Save</button>
  </form>
</div>