我正在使用Asp.Net Core MVC进行不显眼的验证。我有一个允许为子集合动态添加输入元素的表单,我希望将它们包含在客户端验证中。我已经看到了一些以前的解决方案,例如Adding jQuery validator rules to dynamically created elements in ASP,但客户端验证仍不会发生。为子集合验证动态添加的输入元素
这是我的代码。首先,一个html块被克隆,并在单击按钮时附加到表单列表中。
<li class="newVideoRow well-sm">
<div>
<input type="hidden" name="Videos.Index" value="#" />
<label>Video Title:</label>
<input name="Videos[#].VideoTitle" class="videoTitle form-control inline" placeholder="Enter a short title for this video" value="" />
</div>
<div>
<label>Video Link:</label>
<input name="Videos[#].VideoUri" type="url" class="videoUri form-control inline" value="http://" />
</div>
</li>
jQuery的用于克隆的列表项元素然后操纵[#]索引增加了验证属性和可能重新解析不显眼的验证器。
$('#addNewVideo').click(function(){
var nr = $('.newVideoRow').clone();
nr.removeClass('newVideoRow').addClass('videoRow');
var index = (new Date).getTime();
$(nr).find('div input').each(function(divIndex, divElement){
$(divElement).attr('name', $(divElement).attr('name').replace('#', index));
var inputName = $(divElement).attr('name');
if ($(divElement).attr('type') != 'hidden'){
$(divElement).attr('data-val', 'true');
$(divElement).attr('data-val-required', 'A value is required');
$(divElement).after('<span asp-validation-for="' + inputName + '" data-valmsg-replace="true" class="text-danger field-validation-valid"></span>');
$('form').removeData('validator').removeData('unobtrusiveValidation');
//Parse the form again
$.validator.unobtrusive.parse($('form'));
}
$(divElement).val($(divElement).val().replace('#', index));
});
$('#videoList').append(nr);
});
$('form').submit(function(e){
saveSubmitValues(); // copies some other values to hidden fields
});
如果我离开加入的输入为空白,并提交,该HTML5 URL型输入检测到错误,但所需的VideoTitle字段不显示错误。任何人都可以检测到我出错或建议解决方案吗?