gpt4 book ai didi

jquery - 通过 jQuery 在 MVC 3 中克隆输入和验证

转载 作者:行者123 更新时间:2023-12-03 22:59:52 25 4
gpt4 key购买 nike

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

这是我的 View 代码:

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

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

最佳答案

这几行对我有帮助:

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

关于jquery - 通过 jQuery 在 MVC 3 中克隆输入和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10497693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com