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.
What is the purpose of ValidationContext when implementing IValidatableObject
-
24-03-2022 - |
Вопрос
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.
Решение
Другие советы
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"});
}
}
Не связан с StackOverflow