jQuery validation fails when using KnockoutJS and Jquery dialog
I have a form which is rendered using html.RenderAction in MVC3.
Outside of this I have a jquery template used with knockout. The model is rendered correctly into the view with the default 'data-val-required' attributes.
However I've noticed that jQuery validation always returns true.
<div id="dlgAdd" data-bind="template: { name: 'editTemplate', data: selected }">
</div>
<script id="editTemplate" type="text/html">  
<div> 
@{
    Html.RenderAction("EditDialog");
}
</div>    
</script>
The EditDialog partial renders the following output like so:
 <form method="post" id="frmAddNew" action="/Project/AddNew"> 
    <div class="fields-inline">         
       <div class="editor-label">             
          <label for="Name">Name</label>         
       </div>         
       <div class="editor-field">
          <input data-val="true" data-val-required="The Name field is required." id="Name" name="ko_unique_41" value="" type="text">
          <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
       </div>
    </div>
    <span id="validationmessage" class="field-validation-error"></span> 开发者_高级运维  
  </form>
However, when I call $("#frmAddNew").valid()), it always returns 'true'.
I don't know if its knockout, jQuery or mvc which is preventing the validation from returning false.
Try calling $.validator.unobtrusive.parse(yourFormElement) to get your data- attributes related to validation parsed.
You could trigger it like:
<div id="dlgAdd" data-bind="template: { name: 'editTemplate', data: selected, afterRender: hookUpValidation  }">
</div>
then, hookUpValidation would look like:
hookUpValidation: function(nodes) {
    $.validator.unobtrusive.parse(nodes[0]);
}
I have looked into the code of jQuery validate and I think it doesn't work for dynamically added forms (which what Knockout does).
Take a look at this > Jquery Validation Plugin, dynamic form validation
You need to call the validate() method in a an event handler registered using the jQuery live() method. The live method links to all the dynamically added elements as well.
Let me know if it works.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论