使用JQuery验证来验证动态的不同元素

时间:2019-07-02 16:30:26

标签: jquery jquery-validate

我想制作一个动态调查表,其中包含三个问题:姓名,年龄和电子邮件,这三个问题具有不同的验证规则。最近,我发现无法对不存在的元素使用rules,而且我发现了几个如何动态添加规则的示例,但如何仅在具有相同验证规则的相同动态元素上添加规则。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
    <div class="questions">
      <form id="form1">
        <h5>Your Name</h5>
        <input type="text" id="name" name="name" placeholder="Name"/>
        <input type="submit" value="Next" class="btn" id="next" data-nextthing="question2">
      </form>
      <script src="app.js"></script>
    </div>

app.js

$(function() {
    let myApp = {};
        $('form').validate({
         rules: {
           name: {
              required: true,
              maxlength: 5,
           }
         },
         messages: {

           name: {
               required: "Name is required",
               maxlength: "Max legth is 5"
           }
         },submitHandler: function (form) {
                 alert('valid form -> ajax');
                 // your ajax here
                 return false;
          }

       });
   //Templates

    myApp.question2 = ` 
    <h5>Your Age</h5>
  <form id="form2">I am 2
      <input type="number" id="age" name="age" placeholder="age">
      <input type="submit" id="next2"  class="btn" data-nextthing="question3">
    </form>
  `;
    myApp.question3 = ` 
  <h5>Your Email</h5>  
  <form id="form3">I am 3
     <input type = "email" id="email" name="email" placeholder="email">
     <input type="submit" id="next3"  class="btn" data-nextthing="question1">
   </form>
   `;

    myApp.question1 = $(".questions").html(); // just to store it
    $(".questions")
      .on('click submit','.btn', function(event) {
        event.preventDefault();
        console.log("this", $(this));
        let form1 = $(this)[0].parentElement; // get actual form

        console.log("form", $(form1));

        if ($(form1).valid()){
          let actualForm = $(form1).attr('id'); // Get the Id of actual form
          if (actualForm == 'form3'){
            form1.submit(); //Submit the last form :P
            return false;
          }


          let d = $(this).data('nextthing'); //Get the next elemt
          $(event.delegateTarget).html(myApp[d]); // load it in DOM
          return false;
        }

      });
    });

CODEPEN:

https://codepen.io/anon/pen/JQvJVY

编辑:

是的,主要问题是我可以动态添加元素,但是验证不适用于新元素。我知道有一个add方法在我的代码中无法实现。

完成代码后,首先我必须知道DOM中加载了什么元素,然后必须应用与其对应的规则。

我将代码更改为此。

   $(".questions")
      .on('click submit','.btn', function(event) {
        event.preventDefault();
        //console.log("this", $(this));
        let form1 = $(this)[0].parentElement;
        let actualForm = $(form1).attr('id');

          if (actualForm == 'form2'){
            $('#age').rules('add', { 
                required: true, 
                maxlength: 2
            });
          }
          if (actualForm == 'form3'){
            $("#email").rules('add',{
                email: {
                    required: true,
                    email: true
                  }
            });

        if ($(form1).valid()){
          if (actualForm == 'form3'){
            form1.submit();

          } else {
            let d = $(this).data('nextthing');
            $(event.delegateTarget).html(myApp[d]);

          }
          return false;

        }

        });

      });  

但是我有一个错误TypeError: a.data(...) is undefined,我不知道是否正确添加了规则,或者元素是否失去作用域。

https://codepen.io/anon/pen/ewrGxV

0 个答案:

没有答案