ASP.NET Core MVC Interview Question #168
What is a custom validation attribute?
Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced
Quick Interview Answer
A custom validation attribute derives from ValidationAttribute and implements reusable validation logic that can be applied declaratively to model properties or types.
Detailed Explanation
A custom validation attribute derives from ValidationAttribute and implements reusable validation logic that can be applied declaratively to model properties or types.
Custom validation attributes work best for self-contained validation rules. Rules requiring database access, authorization context, or complex domain behavior are usually better handled by application/domain validation services rather than service-heavy attributes.
Code Example
public sealed class NotFutureDateAttribute
: ValidationAttribute
{
public override bool IsValid(object? value)
{
return value is not DateTime date ||
date.Date <= DateTime.UtcNow.Date;
}
}