1

Suppose I have a model which I need to validate. I can add some validate attributes to the properties I want to validate. And it works pretty fine. But at some point I want to validate this model depending on other models (I will need t query db). And here there are some options.

  • create a special validate attribute which will lack dependency injection
  • delegate this validation to some business layer (manager) and in controller

_

if (Model.IsValid) {
    if(!await Manager.Create(myModel)) {
        Model.CopyErrors(Manager.Errors); // Extension method for Model
    }
}

So what is the correct way of handling such a situation?

P.S. I am using asp.net core and entity framework core

2
  • If your validation needs to check data on db, not only if user passed numbers instead of strings you'll need something more complex. Usually, for validation that don't require database, use fluent validation as suggested. Is the most straightforward way to go and every dev knows about it. Don't reinvent the wheel yourself. Commented Jul 10, 2017 at 15:40
  • The second level of validation you could have is having decorators around your Manager.Create method. I assume Manager is sort of a repository or other layer. Using Autofac for instance, you can register Decorators around your repository and when you call Create, the decorator chain will execute. Commented Jul 10, 2017 at 15:41

1 Answer 1

1

What you need is Fluent Validation

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

2 Comments

in fact I don't want to use third-party validation library. I want to know how it should be handled with what I have
@arthur.borisow up to you, but Fluent Validation is de facto for handling complex validation tasks in asp.net mvc.

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.