In last article, we have seen what a model binding is and how validation attributes can be used with models to enable model validations.
.NET provides validation attributes for almost all basic validations. But in real world applications, sometimes you may come across some situation, where built-in attributes would not be sufficient. In this article, we are going to look at what are options in those cases.
First option is to create custom validation attribute. ValidationAttribute is an abstract class and it is used as base class for all the built-in validation attributes.
To better understand how the custom implementation should be, let’s take an example.
Let’s say, the minimum salary requirements for people less than 30 is
$50 per hour and minimum salary requirement for people greater than 30 years is
$200. So this validation is supposed to read date of birth. But this validation is supposed to be placed on
HourlySalary property of model.
This validation can be implemented using the custom validation attribute as shown in below code.
Same validation from custom attributes section can be implemented using IValidatableObject as shown in below code.
Below code shows a validation for date of birth. People with age more than 65 years cannot be accepted by system (as they are supposed to be retired by then).
Below code shows both custom validation attribute and IValidatableObject implemented for Employee model. Full working example can be downloaded from my GitHub repository.
Which one is better ?
Short answer – It really depends !
When a custom validation attribute is created, the logic of validation is outside the class. So it can be reused easily by just placing attribute on any model property.
When IValidatableObject is implemented in model, the validation logic is inside the model. So reusing is not possible – or – if not possible completely, then it is difficult at least.
So, which one should be used ? Various aspects can be checked to decide which option can be best suitable for the scenario. Those aspects may include reusability, ease of implementation or maintainability of the solution.
- If there are chances of reusing the validation logic, then I would prefer validation attributes.
- Some may always use IValidatableObject because it keeps the validation logic inside the model it is being used for.
- Also, sometimes, ease of implementation can also be another driving factor.
When in doubt, I would personally prefer creating a custom validation attribute.
Do you share different opinions ? Let me know your thoughts.