1

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

cmorganmcp
  • 38
  • 1
  • 6

3 Answers3

0
dates.rules("add", {
    required: true,
    messages: {
        required: "Please select a date"
    }
});

This works for me. Perhaps you need to inject those elements to the DOM first and then set the validation...

Achilles
  • 1,554
  • 1
  • 28
  • 36
0

Try this:

$.validator.unobtrusive.parse('#ShiftDate');

Perhaps you need to specify to attach to the form:

$.validator.parseElement.parse($('#ShiftDate').get(),false);

Mark Perry
  • 1,705
  • 10
  • 12
  • No luck, the form is still treated as valid with nothing selected, even when calling validate manually. – cmorganmcp Jul 12 '11 at 14:38
  • Try using `$.validator.parseElement.parse($('#ShiftDate').get(),false);` – Mark Perry Jul 12 '11 at 14:43
  • 1
    that throws an error as written but I tried what you were going for and again, no luck.... [this other thread](http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements) may hold the solution.... – cmorganmcp Jul 12 '11 at 15:58
0

Is your select list within a form context?

Lee Smith
  • 6,339
  • 6
  • 27
  • 34