I am using Asp.Net Core MVC with unobtrusive validation. I have a form which allows dynamic addition of input elements for a child collection and I want to include these in client-side validation. I've seen some of the previous solutions for this e.g. Adding jQuery validator rules to dynamically created elements in ASP, but the client validation still doesn't take place.
Here is my code. First an html block is cloned and appended to a form list when a button is clicked.
<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>
The jQuery for the cloned list item elements then manipulates the [#] index adds validation attributes and presumably re-parses the unobtrusive validator.
$('#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
});
If I leave the added inputs blank and submit, the html5 url-type input detects an error but the required VideoTitle field doesn't display an error. Can anyone detect where I am going wrong or suggest a solution?