我正在使用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字段不顯示錯誤。任何人都可以檢測到我出錯或建議解決方案嗎?