What is the purpose of ValidationContext when implementing IValidatableObject
Asked Answered
A

2

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.

Adenovirus answered 19/3, 2013 at 12:2 Comment(0)
V
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.

Vinia answered 19/3, 2013 at 12:52 Comment(4)
It helps to give an example about how to pass a DI container in this particular situation.Sporocyst
in asp.net mvc this can be done with creating your own validation provider.Vinia
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 :(Systematism
This blog post shows how to use ValidationContext to get a service via DI. Basically: var service = (IExternalService) validationContext.GetService(typeof(IExternalService));Beryllium
K
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"});
    }
 }
Kidney answered 19/3, 2013 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.