Reputation: 2702
What are the benefits to using custom data validations in the form of attributes for our models, versus making those validation checks in the action of the controller?
A small example.
public class CollectionHasElementsAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is IList<string> stringCollection)
{
return stringCollection.Count > 0
}
return false;
}
}
versus
public IActionResult someAction(List<string> stringCollection)
{
if (stringCollection.Count <= 0)
{
// return your error the way you want to here
}
}
Upvotes: 0
Views: 111
Reputation: 4159
The main reason would be simplicity and following the principle DRY. Lets say you have 10 controllers which performs your business logic using List<string> stringCollection
,now you have to manually write if()
do this again and again in all 10 Controllers.
With a attribute you just write if()
only once inside where the validation is done and just add the attribute.
A better alternative to writing your own validation conditions is using a library like FluentValidation
-> Docs
If you want to see some more amazing libraries like this, checkout this list
Upvotes: 1