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
}
}