2015-02-05 64 views
3

我想解析一個動態插入的表單來添加jQuery不顯眼的驗證。jQuery unobtrusive驗證沒有觸發動態內容加載

我這是當用戶搜索執行以下功能AJAX:

function search(el) 
{ 
    var $this = $(el); 
    var $form = $this.closest("form"); 
    var url = $form.attr("action"); 
    $results = $("#pnlSearchResults"); 

    $.ajax({ 
     type: "POST", 
     url: url, 
     data: $form.serialize() 
    }) 
    .done(function(data){ 
     $results.html(''); 
     $results.html(data); 

     var $editForm = $results.find("form.edit-form"); 
     $editForm.removeData("validator"); 
     $editForm.removeData("unobtrusiveValidation"); 
     $.validator.unobtrusive.parse($editForm); 
    }); 
} 

這將插入一個可編輯的形式返回實體到<div>它看起來像這樣在頁面上。我有兩個必需的字段,但是當我從這些字段中刪除值時,「必需」驗證不會觸發。它似乎只發生在:

  1. 我刪除這些值。
  2. 將光標移離現場。
  3. 輸入一個新值。
  4. 將光標移開。
  5. 然後刪除新的值。

我該如何解決這個問題,以便在第一次刪除該值時進行驗證?

回答

0

我發現this question,這導致我回答了this page

(function ($) { 
    $.validator.unobtrusive.parseDynamicContent = function (selector) { 
    //use the normal unobstrusive.parse method 
    $.validator.unobtrusive.parse(selector); 

    //get the relevant form 
    var form = $(selector).first().closest('form'); 

    //get the collections of unobstrusive validators, and jquery validators 
    //and compare the two 
    var unobtrusiveValidation = form.data('unobtrusiveValidation'); 
    var validator = form.validate(); 

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) { 
     if (validator.settings.rules[elname] == undefined) { 
     var args = {}; 
     $.extend(args, elrules); 
     args.messages = unobtrusiveValidation.options.messages[elname]; 
     //edit:use quoted strings for the name selector 
     $("[name='" + elname + "']").rules("add", args); 
     } else { 
     $.each(elrules, function (rulename, data) { 
      if (validator.settings.rules[elname][rulename] == undefined) { 
      var args = {}; 
      args[rulename] = data; 
      args.messages = unobtrusiveValidation.options.messages[elname][rulename]; 
      //edit:use quoted strings for the name selector 
      $("[name='" + elname + "']").rules("add", args); 
      } 
     }); 
     } 
    }); 
    } 
})($); 

用法:

var html = "<input data-val='true' "+ 
      "data-val-required='This field is required' " + 
      "name='inputFieldName' id='inputFieldId' type='text'/>"; 
$("form").append(html); 

$.validator.unobtrusive.parseDynamicContent('form input:last');