Manually wiring up unobtrusive jquery validation client-side without Model/Data Annotations, MVC3
- by cmorganmcp
After searching and experimenting for 2 days I relent. What I'd like to do is manually wire up injected html with jquery validation. I'm getting a simple string array back from the server and creating a select with the strings as options. The static fields on the form are validating fine. I've been trying the following:
var dates = $("<select id='ShiftDate' data-val='true' data-val-required='Please select a date'>");
dates.append("<option value=''>-Select a Date-</option>");
for (var i = 0; i < data.length; i++) {
dates.append("<option value='" + data[i] + "'>" + data[i] + "</option>");
}
$("fieldset", addShift).append($("<p>").append("<label for='ShiftDate'>Shift Date</label>\r").append(dates).append("<span class='field-validation-valid' data-valmsg-for='ShiftDate' data-valmsg-replace='true'></span>"));
// I tried the code below as well instead of adding the data-val attributes and span manually with no luck
dates.rules("add", {
required: true,
messages: {
required: "Please select a date"
}
});
// Thought this would do it when I came across several posts but it didn't
$.validator.unobtrusive.parse(dates.closest("form"));
I know I could create a view model ,decorate it with a required attribute, create a SelectList server-side and send that, but it's more of a "how would I do this" situation now. Can anyone shed light on why the above code wouldn't work as I expect?
-chad