Mister Epic
Mister Epic

Reputation: 16743

MVC Validation: Service Layer or Data Annotations

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

Upvotes: 3

Views: 2000

Answers (2)

Felipe Oriani
Felipe Oriani

Reputation: 38618

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
}

Upvotes: 3

Max Toro
Max Toro

Reputation: 28618

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.

Upvotes: 1

Related Questions