MVC Custom Validation for List on Client Side

The reason you will not get client side validation is because the html helpers generate data-val-* attributes for controls associated with properties. jquery.validate.unobtrusive reads those attributes when the form is parsed and using rules, displays an error message in the appropriate element generated by ValidationMessageFor() associated with that control (it does this by matching up the id attributes of the elements – the error message is generated in a span with <span for="TheIdOfTheAssociatedControl" ...>).

You don’t (and cant) generate a control for property DeclarationQuestions (only for properties of each item in DeclarationQuestions so there is nothing that can be matched up.

You could handle this by including your own error message placeholder and intercepting the .submit event

html (add css to style #conditions-error as display:none;)

<span id="delarations-error" class="field-validation-error">
  <span>You must accept all declarations to continue.</span>
</span>

Script

var declarationsError = $('#delarations-error');
$('form').submit(function() {
  var isValid = $('.yourCheckBoxClass').not(':checked') == 0;
  if(!isValid) {
    declarationsError.show(); // display error message
    return false; // prevent submit
  }
});

$('.yourCheckBoxClass').change(function() {
  if($(this).is(':checked')) {
    declarationsError.hide(); // hide error message
  }
});

Side note: You loop for generating the checkboxes should be

for (int i = 0; i < Model.DeclarationQuestions.Count; i++)
{
  @Html.CheckBoxFor(m => m.DeclarationQuestions[i].Answer, new { id = "DeclarationQuestions" + i})
}

Leave a Comment