16

I have implemented IValidatableObject several times and have never found out what the purpose of parsing ValidationContext to the Validate method is - my typical IValidatableObject implementation looks something like this:

 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
    if (Prop1 == Prop2)
    {
        yield return new ValidationResult(
              "Prop1 and Prop2 must be different.",
              new[] {"Prop1", "Prop2"});
    }
 }

Is there anything that I have missed that I could have used validationContext for?

EDIT: I'm using ASP.NET MVC and this is implemented in the class - not in the controller.

Henrik Stenbæk
  • 3,982
  • 5
  • 31
  • 33

2 Answers2

9

ValidationContext contains IServiceProvider property. It is extension point to pass DI container to your validation attributes and Validate methods. You can use it, as example, to validate against database without setting dependency on dbcontext in your model.

Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • 7
    It helps to give an example about how to pass a DI container in this particular situation. – Stack0verflow May 14 '14 at 12:36
  • in asp.net mvc this can be done with creating your own validation provider. – Kirill Bestemyanov May 15 '14 at 06:05
  • 3
    Can you please give an example of this?? I'm really stuck trying to make validations properly and to see a potencial answer without code is really sad :( – Felipe Correa Aug 21 '15 at 21:43
  • This [blog post](https://andrewlock.net/injecting-services-into-validationattributes-in-asp-net-core/) shows how to use `ValidationContext` to get a service via DI. Basically: `var service = (IExternalService) validationContext.GetService(typeof(IExternalService));` – bvpb Oct 12 '17 at 05:08
6

You should retrieve Prop1 and Prop2 from validationContext. From your question it's difficult to say whether you are using WebForms (so you have code-binding with properties) or MVC (and if you are implementing this in the controller).

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
    if (validationContext["Prop1"] == validationContext["Prop2"])
    {
        yield return new ValidationResult(
              "Prop1 and Prop2 must be different.",
              new[] {"Prop1", "Prop2"});
    }
 }
usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305