所有
我需要将验证规则添加到用户添加的动态表单输入文本元素中。
我通过克隆一大块HTML,提供独特的ID并添加到DOM来实现这一目标
我研究了这个的语法,我认为这是正确的但是当我尝试访问 .rules 方法时,我收到以下JS错误:
TypeError: $(...).rules is not a function
由此引起:
$("input[type=text].validateRequired").each(function () {
$(this).rules("add", { required: true, messages: { required: "Data is missing" }
});
});
当我在FireBug中检查$(this)
时,我没有看到.rules方法,但它存在于验证脚本中,并且所有文档都显示该方法应该全局可用。不确定如何将其纳入范围。
以下是与此问题相关的视图中的代码:
JS包含
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
创建动态表单元素的JS方法
<script type="text/javascript">
$(document).ready(function() {
var uniqueId = 1;
var ctr = 1;
$(function() {
$('.js-add-cosponsor-hyperlink').click(function() {
var copy = $("#cosponsorsTemplate").clone(true).appendTo("#addCosponsorSection").hide().fadeIn('slow');
var cosponsorDivId = 'cosponsors_' + uniqueId;
var copyText = copy.html();
copyText = copyText.replace(/Guitar1/g, 'Guitar' + ctr);
copyText = copyText.replace('Guitar_1', 'Guitar_' + ctr);
copy.html(copyText);
$('#cosponsorsTemplate').attr('id', cosponsorDivId);
var deleteLink = copy.find("a.icon.delete");
deleteLink.on('click', function() {
copy.fadeOut(300, function() { $(this).remove(); }); //fade out the removal
});
$.validator.unobtrusive.parse(form);
$("input[type=text].validateRequired").each(function () {
var t = $(this);
$(this).rules("add", { required: true, messages: { required: "Data is missing" } });
});
uniqueId++;
ctr++;
});
});
});
</script>
* 表格 *
@using (Html.BeginForm())
{
[...]
<!-- Template used to do the Clone: These need dynamic validation -->
<div style="display:none">
<div id="cosponsorsTemplate">
<div class="formColumn1"><label>Guitar</label></div>
<div class="formColumn2">@Html.TextBoxFor(model => model.Guitar1.Make, new { Placeholder = "Make", Class = "validateRequired" })
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Guitar1.Make)
</div>
</div>
<div class="formColumn3">@Html.TextBoxFor(model => model.Guitar1.Model, new { Placeholder = "Model" , Class = "validateRequired"})
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Guitar1.Model)
</div>
</div>
<div class="formColumn4">@Html.TextBoxFor(model => model.Guitar1.ProductionYear, new { Placeholder = "Production Year", Class = "validateRequired" })
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Guitar1.ProductionYear)
</div><a class="icon delete">Delete</a>
</div>
</div>
</div>
<!-- End Add Co-Sponsor Row Template -->
}
答案 0 :(得分:0)
您正在克隆一大块HTML,因此每次进行克隆时都需要解析整个表单 使用$ .validator.unobtrusive.parse