Since I had jQuery creating elements on the fly, I couldn't just apply attributes to my model and have the web server sort the rest, I had to make the jQuery Validate plugin understand that I wanted these elements validated and so I found the following.
Make sure you have the name, data-val and data-val-required attributes set:
<input type="text" name="contents_1" class="form-control" placeholder="Contents" data-val="true" data-val-required="Please enter the value for pack 1." />
Just remember that you MUST have all the attributes in bold above applied to all elements that you want to validate. Obviously updating the name and data-val-required text for each element.
var elem = $("<input type=\"text\" name=\"contents_" + rowid + "\" class=\"form-control\" placeholder=\"Contents\" data-val=\"true\" data-val-required=\"Please enter the value for pack " + rowid + ".\" />");
Then it's just a case of removing validation from the form and adding it again:
// Remove validation. $("form").removeData("validator").removeData("unobtrusiveValidation"); // Add validation again. $.validator.unobtrusive.parse("form");
Find out more about the DOM here: https://www.w3.org/TR/DOM-Level-2-Core/introduction.html
Useful Stack Overlow article on just this: http://stackoverflow.com/questions/9386971/adding-jquery-validator-rules-to-dynamically-created-elements-in-asp
Get unobtrusive validation here: https://github.com/aspnet/jquery-validation-unobtrusive
By Luke Alderton at 29 Mar 2017, 05:49 AM