0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I know this is slightly off-topic, but are ValidationAttributes executed in the order you write them over properties/fields/etc, or is it at random?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.