Paul
Paul

Reputation: 1875

jQuery tools validator, how to make it work with dynamically added elements?

I am trying to use jQuery Tools Validator to implement the form validation.

My form isn't simple and it consists of two steps:

  1. Initial fields are presented, validator is initialized to make sure right values are entered and required fields are filled.
  2. After all fields values are provided and submit button is clicked, I do json request and depending on the result add new input fields with their corresponding validations attributes and cancel the submit action. When the button is clicked with new fields then the form is submitted.

The thing is the validator doesn't seem to know about the new inputs to validate. how do I refresh it and make validator aware of dynamically added inputs?

I tried

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

But no luck.

Any suggestions?

Upvotes: 0

Views: 2557

Answers (2)

Virtual Innovators
Virtual Innovators

Reputation: 34

I would love to solve the problem using the power of unbind function( http://api.jquery.com/unbind/ ).The good part of this solution is that we don't have to attach the newly added fields to the validator object manually.The full code is given below:

/* server-side.html file */

<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"
}

You can try this code to make the functionality more dynamic.Enjoy :)

Upvotes: 1

Paul
Paul

Reputation: 1875

Well, as I figured new elements are not attached to the existing validator object.

Therefore the way to go was to init validator for new created fields and hook up form's submit event to execute validation from code:

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

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

This worked just fine.

Upvotes: 0

Related Questions