Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
jaffa Avatar asked Apr 14 '11 12:04

jaffa


1 Answers

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]);
}
like image 175
RP Niemeyer Avatar answered Nov 30 '22 05:11

RP Niemeyer