title: MVC Custom Validation for List on Client Side
body: <p>I'm trying to write a custom validator that works on the client side that validates that all checkboxes have been ticked. </p>
  
  <p>Here's the declaration on the model: </p>
  
  <pre><code>[DeclarationsAccepted(ErrorMessage = "You must tick all declarations")]        
      public IList&lt;DeclarationQuestion&gt; DeclarationQuestions { get; set; }
  </code></pre>
  
  <p>And here's the attribute: </p>
  
  <pre><code>public class DeclarationsAccepted : ValidationAttribute, IClientValidatable
  {
      protected override ValidationResult IsValid(object value, ValidationContext validationContext)
      {
  
          var questions = value as IList&lt;DeclarationQuestion&gt;;
  
          if (questions != null &amp;&amp; questions.All(c =&gt; c.Answer))
          {
              return ValidationResult.Success;
          }
          return new ValidationResult("You must accepted all declarations to continue");
      }
  
      public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
      {
          var modelClientValidationRule = new ModelClientValidationRule
          {
              ValidationType = "declarationsaccepted",
              ErrorMessage = FormatErrorMessage(metadata.DisplayName)
          };            
          yield return modelClientValidationRule;
      }
  }
  </code></pre>
  
  <p>So far so good, works server side. </p>
  
  <p>For the client I'm wiring this up as follows: </p>
  
  <pre><code>jQuery.validator.addMethod('declarationsaccepted', function (value, element, params) {
  
          //Implement logic here to check all boxes are ticked
          console.log(value);
  
          return false;
      }, '');
  
  
      jQuery.validator.unobtrusive.adapters.add('declarationsaccepted', {}, function (options) {
          options.rules['declarationsaccepted'] = true;
          options.messages['declarationsaccepted'] = options.message;
      });
  </code></pre>
  
  <p>I'm displaying the checkboxes like this: </p>
  
  <pre><code>@{ var questionIndex = 0; }
          @foreach (var question in Model.DeclarationQuestions)
          {
  
                  @Html.CheckBoxFor(model =&gt; Model.DeclarationQuestions[questionIndex].Answer, new { id = "DeclarationQuestions" + questionIndex})
  
              questionIndex++;
          }
  </code></pre>
  
  <p>And then displaying the validation message using this: </p>
  
  <pre><code>@Html.ValidationMessageFor(c =&gt; c.DeclarationQuestions)
  </code></pre>
  
  <p>When I submit the form the message is displayed but only after a post back to the server. Is there any way to get this to work on the client side?</p>