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.
Interface ValidationContextA context for a validator to use to access user data and report validation failures.
When you click on "Implement interface 'IValidatableObject'" you will have the following interface. This will return IEnumerable<ValidationResult> by taking one parameter as ValidationContext.
This class describes the type or member on which validation is performed. It also enables custom validation to be added through any service that implements the IServiceProvider interface. Initializes a new instance of the ValidationContext class using the specified object instance.
Other validations will be executed eventually only if [Required] validation has been passed. And IValidatableObject takes the lowest priority. It’s going to be called only if there’s no [Required] error and no other errors like [Range].
This validation can be implemented using the custom validation attribute as shown in below code. Another option to apply custom validations is to implement interface – IValidatableObject – in model class. This interface provides a method – Validate – which can be implemented in the class.
ValidationAttribute is an abstract class and it is used as base class for all the built-in validation attributes. If a custom validation attribute is required, create a new class which extends ValidationAttribute. Next, override the abstract method – IsValid – to implement custom validation logic.
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"});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With