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.

有帮助吗?

解决方案

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.

其他提示

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"});
    }
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top