4

我使用MVC3模型驗證和不顯眼驗證 並嘗試找到某種方法來克隆元素和驗證。通過jQuery在MVC 3中克隆輸入和驗證

這是我的看法代碼:

<div id="d1" class="Addable"> 
@Html.EditorFor(model => model.CellPhone) 
@Html.ValidationMessageFor(model => model.CellPhone) 
</div> 
<input type"button" class="AddE" /> 

和HTML DOM是:

<div class="Addable" id="d1"> 
    <input type="text" value="" name="CellPhone" id="CellPhone" data-val-required="Req." 
    data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true" 
    class="text-box single-line valid"> 

<span data-valmsg-replace="true" data-valmsg-for="CellPhone" 
    class="invalid-side-note field-validation-valid"></span> 
</div> 

所以我用下面的腳本來克隆新的變革的名字,如數組名:

//Add new Addable div 
$('.AddNewE').click(function() { 

    var Target = $('.Addable:first'); 
    var TargetId = $(Target).attr('id'); 
    var Count = $('.Addable#' + TargetId).size(); 
    var CloneTarget = $(Target).clone(); 
    CloneTarget.find('input').val(''); 
    CloneTarget.insertAfter('.Addable:last'); 
    var TargetName = $(Target).find('input').attr('name'); 

    if (Count == 1) { 

     var CloneName = TargetName + '[1]'; 
     TargetName = TargetName + '[0]'; 

     $(Target).find('input').attr('name', TargetName); 
     $(Target).find('span[class|="field-validation"]').attr('data-valmsg-for', TargetName); 

     $(CloneTarget).find('input').attr('name', CloneName); 
     $(CloneTarget).find('span[class|="field-validation"]').attr('data-valmsg-for', CloneName); 

    } else { 

     var indx = TargetName.length - 3; 
     var CloneTargetName = TargetName.substring(0, indx); 
     CloneTargetName = CloneTargetName + '[' + Count + ']'; 
     $(CloneTarget).find('input').attr('name', CloneTargetName); 
     $(CloneTarget).find('span[class|="field-validation"]').attr('data-valmsg-for', CloneTargetName); 
    } 

}); 

第一次克隆後,Dom是:

<div class="Addable" id="d1"> 
    <input type="text" value="" name="CellPhone[0]" id="CellPhone" data-val-required="Req." 
    data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true" 
    class="text-box single-line valid"> 

<span data-valmsg-replace="true" data-valmsg-for="CellPhone[0]" 
    class="invalid-side-note field-validation-valid"></span> 
</div> 


<div class="Addable" id="d1"> 
    <input type="text" value="" name="CellPhone[1]" id="CellPhone" data-val-required="Req." 
    data-val-regex-pattern="^04[1234][0-9]{6}$" data-val-regex="notValid" data-val="true" 
    class="text-box single-line valid"> 

<span data-valmsg-replace="true" data-valmsg-for="CellPhone[1]" 
    class="invalid-side-note field-validation-valid"></span> 
</div> 

我更改了驗證跨度和輸入,因爲每個輸入都會有自己的驗證。 但克隆後驗證沒有奏效。哪裏有問題?你的建議是什麼?

回答

8

此行幫助我:

 $('form').removeData('validator'); 
     $('form').removeData('unobtrusiveValidation'); 
     $.validator.unobtrusive.parse('form');