jQuery工具验证器,如何使其与动态添加的元素一起工作?

时间:2012-01-06 22:15:56

标签: javascript jquery validation jquery-tools

我正在尝试使用jQuery Tools Validator来实现表单验证。

我的表单并不简单,它包含两个步骤:

  1. 显示初始字段,初始化验证程序以确保输入正确的值并填写必填字段。
  2. 提供所有字段值并单击提交按钮后,我会执行json请求,并根据结果添加新输入字段及其相应的验证属性,并取消提交操作。当使用新字段单击按钮时,表单将被提交。
  3. 问题是验证器似乎不知道要验证的新输入。如何刷新它并使验证器知道动态添加的输入?

    我试过

    form.data("validator").destroy();
    form.validator();
    

    但没有运气。

    有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我很乐意使用unbind函数(http://api.jquery.com/unbind/)来解决这个问题。这个解决方案的好处是我们不必手动将新添加的字段附加到验证器对象。完整代码如下:

/ * server-side.html文件* /

<html>

<!--
    This is a jQuery Tools standalone demo. Feel free to copy/paste.

    http://flowplayer.org/tools/demos/

    Do *not* reference CSS files and images from flowplayer.org when in production  

    Enjoy!
-->

<head>
    <title>jQuery Tools standalone demo</title>

    <!-- include the Tools -->
    <script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>


    <!-- standalone page styling (can be removed) -->
    <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/standalone.css"/>   


    <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/demos/validator/css/form.css"/>

</head>

<body>


<form id="myform">

   <fieldset>
      <h3>Sample registration form</h3>

      <p> Enter bad values and then press the submit button. </p>
      <p>
         <label>website *</label>
         <input type="url" name="url" required="required" />
      </p>
      <p>
         <label>name *</label>
         <input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" />
      </p>
      <p>
         <label>age</label>
         <input type="number" name="age" size="4" min="5" max="50" />
      </p>

      <p id="terms">
        <label>I accept the terms</label>
        <input type="checkbox" required="required" />   
        </p>

      <button type="submit">Submit form</button>
      <button type="reset">Reset</button>
   </fieldset>

</form>


<script>

// initialize validator and add a custom form submission logic
var submitEvent = function(){$("#myform").validator().submit(function(e) {

    var form = $(this);

    // client-side validation OK.
    if (!e.isDefaultPrevented()) {

        // submit with AJAX
        $.getJSON("server-fail.js?" + form.serialize(), function(json) {

            // everything is ok. (server returned true)
            if (json['valid'] === 'true')  {
                if($("#testField").length == 0){
                    $("#terms").before('<p> <label id="testField">email *</label><input type="email" name="email" required="required" /></p>');
                }
                else {
                alert("new field validated successfully");
                }

                form.unbind("submit"); 
                submitEvent();

            // server-side validation failed. use invalidate() to show errors
            } else {
                form.data("validator").invalidate(json);
            }
        });

        // prevent default form submission logic
        e.preventDefault();
    }
});};
submitEvent();
</script>
</body>

</html>

<html> <!-- This is a jQuery Tools standalone demo. Feel free to copy/paste. http://flowplayer.org/tools/demos/ Do *not* reference CSS files and images from flowplayer.org when in production Enjoy! --> <head> <title>jQuery Tools standalone demo</title> <!-- include the Tools --> <script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script> <!-- standalone page styling (can be removed) --> <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/standalone.css"/> <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/demos/validator/css/form.css"/> </head> <body> <form id="myform"> <fieldset> <h3>Sample registration form</h3> <p> Enter bad values and then press the submit button. </p> <p> <label>website *</label> <input type="url" name="url" required="required" /> </p> <p> <label>name *</label> <input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" /> </p> <p> <label>age</label> <input type="number" name="age" size="4" min="5" max="50" /> </p> <p id="terms"> <label>I accept the terms</label> <input type="checkbox" required="required" /> </p> <button type="submit">Submit form</button> <button type="reset">Reset</button> </fieldset> </form> <script> // initialize validator and add a custom form submission logic var submitEvent = function(){$("#myform").validator().submit(function(e) { var form = $(this); // client-side validation OK. if (!e.isDefaultPrevented()) { // submit with AJAX $.getJSON("server-fail.js?" + form.serialize(), function(json) { // everything is ok. (server returned true) if (json['valid'] === 'true') { if($("#testField").length == 0){ $("#terms").before('<p> <label id="testField">email *</label><input type="email" name="email" required="required" /></p>'); } else { alert("new field validated successfully"); } form.unbind("submit"); submitEvent(); // server-side validation failed. use invalidate() to show errors } else { form.data("validator").invalidate(json); } }); // prevent default form submission logic e.preventDefault(); } });}; submitEvent(); </script> </body> </html>

/ * server-fail.js file * /

{
  "name": "Invalid name. Our apologies",
  "age": "You are too young",
  "valid": "true"
}

您可以尝试使用此代码使功能更具动态性。享受:)

答案 1 :(得分:0)

好吧,因为我认为新元素没有附加到现有的验证器对象。

因此,要做的就是为新创建的字段初始化验证器并连接表单的提交事件以从代码执行验证:

var input =  $("#newDiv :input").validator();

$("#formId").submit(function(e)
{
     input.data("validator").checkValidity();
});

这很好用。