Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have solved this by handling the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstate_members.aspx" rel="noreferrer">"ModelState"</a> dictionary, which is contained by the controller. The ModelState dictionary includes all the members that have to be validated.</p> <p>Here is the solution:</p> <p>If you need to implement a <strong>conditional validation</strong> based on some field (e.g. if A=true, then B is required), <strong>while maintaining property level error messaging</strong> (this is not true for the custom validators that are on object level) you can achieve this by handling "ModelState", by simply removing unwanted validations from it.</p> <p>...In some class... </p> <pre><code>public bool PropertyThatRequiredAnotherFieldToBeFilled { get; set; } [Required(ErrorMessage = "*")] public string DepentedProperty { get; set; } </code></pre> <p>...class continues...</p> <p>...In some controller action ...</p> <pre><code>if (!PropertyThatRequiredAnotherFieldToBeFilled) { this.ModelState.Remove("DepentedProperty"); } </code></pre> <p>...</p> <p><strong>With this we achieve conditional validation, while leaving everything else the same.</strong></p> <hr> <p><strong>UPDATE:</strong></p> <p>This is my final implementation: I have used an interface on the model and the action attribute that validates the model which implements the said interface. Interface prescribes the Validate(ModelStateDictionary modelState) method. The attribute on action just calls the Validate(modelState) on IValidatorSomething.</p> <p>I did not want to complicate this answer, so I did not mention the final implementation details (which, at the end, matter in production code).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload