MVC Custom Validation for List on Client Side

前端 未结 1 1040
小蘑菇
小蘑菇 2020-11-28 15:38

I\'m trying to write a custom validator that works on the client side that validates that all checkboxes have been ticked.

Here\'s the declaration on the model:

相关标签:
1条回答
  • 2020-11-28 16:03

    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})
    }
    
    0 讨论(0)
提交回复
热议问题