6

我使用 MVC3 模型 Validation 和 Unobtrusive 进行显示验证,并尝试找到一些方法来克隆元素和验证。

这是我的查看代码:

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

我更改了验证范围和输入,因为每个输入都有自己的验证。但克隆后验证根本不起作用。哪里有问题?你的建议是什么?

4

1 回答 1

11

这行帮助我:

        $('form').removeData('validator');
        $('form').removeData('unobtrusiveValidation');
        $.validator.unobtrusive.parse('form');
于 2012-05-08T12:06:33.407 回答