3

I hope this isn't terribly subjective, but when it comes to validating business logic, I see two paths that, unless I'm mistaken, deliver pretty much the same result:

In the first instance, the model is a dumb container for data, and in the second, the model knows about its valid state. Above and beyond that, is there nuance between the two that I'm missing? Should one be used over the other in some instances?

Thanks,

Chris

2 Answers 2

3

In my opinion, you could keep the basic validation (required fields, regex fields, comparative fields etc...) on your Model (InputModel) with Data Annotations or Fluent Validation, and your bussiness validation in service layer. I think the Annotations is much more to create a screen validation and inputs to server side than business validation. If you keep the business at the service layer you must remember to create a ModelState Wrapper to integrate it with Asp.Net MVC, and show it on the view.

Take a look at a samepl of ModelState Wrapper:

public class ModelStateWrapper : IValidationDictionary
{
   private ModelStateDictionary _modelState;
   public ModelStateWrapper(ModelStateDictionary modelState)
   {
      _modelState = modelState;
   }

   #region IValidationDictionary Members

   public void AddError(string key, string errorMessage)
   {
      _modelState.AddModelError(key, errorMessage);
   }

   public bool IsValid
   {
      get { return _modelState.IsValid; }
   }

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

1 Comment

Makes sense, validate attributes that can be examined in isolation with Data Annotations, and validate other rules that integrate with other components via a Service Layer. It's easy once someone points it out :)
1

They are not mutually exclusive, you can use attributes for "static" rules, and service layer validation for "dynamic" rules (e.g. check for uniqueness).

Quoting the tutorial you referred to:

In this tutorial, you learn how to move your validation logic out of your controllers and into a separate service layer.

Well, the model decorated with data annotation attributes does not have to be in the web project next to the controller, it can be in the service layer next to the service, which means all validation logic is in one place.

Comments

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.