IValidatable Object in Asp.net Core

IValidatable Object in Asp.net Core
Data annotations ([Required], [StringLength], etc.) provide a concise way to define validation rules on individual model properties, the IValidatableObject interface allows you to perform more complex, model-level validation logic that spans multiple properties or depends on the entire model’s state.
 
Notes
Interface: IValidatableObject is an interface with a single method: Validate(ValidationContext context).
Validate Method: This method is called by the model binder after individual property-level validations (data annotations) have been checked.
Yielding Errors: Within the Validate method, you can yield ValidationResult objects for any errors you find. This allows you to report multiple errors for the entire model at once.
Model State Integration: The errors you yield are automatically added to the ModelState object, making them available for error display in your views.
 
When to Use IValidatableObject
Cross-Property Validation: When validation logic depends on the values of multiple properties (e.g., “Start Date” must be before “End Date”).
Complex Business Rules: When your validation rules involve complex logic or database lookups.
Customizable Errors: When you want more control over the error messages displayed to the user.
 
Code
// Person.cs (Model)
public class Person : IValidatableObject
{
    // … (properties with data annotations) …
 
    public DateTime? DateOfBirth { get; set; }
    public int? Age { get; set; } // New property
 
    // … (other properties and methods) …
 
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (DateOfBirth.HasValue == false && Age.HasValue == false)
        {
            yield return new ValidationResult(“Either of Date of Birth or Age must be supplied”, new[] { nameof(Age) }); // Yield an error
        }
    }
}
 
In this example:
Implementation of IValidatableObject: The Person class now implements IValidatableObject.
Validate Method:
It checks if either DateOfBirth or Age is provided. If neither is present, it yields a ValidationResult indicating that at least one of these properties must be supplied.
Notice how the error message is specifically associated with the Age property using new[] { nameof(Age) }. This helps target the error message to the correct field in your view.
Model State Update: When you use this model in your controller, the validation errors from the Validate method will automatically be added to the ModelState, and you can check ModelState.IsValid to determine if the model is valid.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply