Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I duplicate validation in my MVC layer and Service layer?

I'm feeling a little conflicted at the moment. I have a web application using Stripes for an MVC framework and Spring/Hibernate for the back-end. I have an account registration method in my MVC layer which requires the following validation:

  • Username is not already taken
  • The provided email address is not already associated with another account

I have a validation method in Stripes (MVC layer) that checks these two cases but was wondering whether my service layer should duplicate these checks? If the service layer interface was exposed as a web service then I think the validation would be a good idea, but if it's only used in the context of a web application is it required?

Edit: I'm not intending to duplicate the validation code - I mean duplicating the validation method calls in two places.

I see my options as:

  1. Duplicate the validation calls in both MVC and service layer
  2. Only perform this validation in the MVC layer
  3. Only perform this validation in the service layer.

What's best practice here? I'm looking for advice/opinions on which option I should go with and why.

Note that there are simple validation checks on the input fields of the registration form (like checking for blanks) and that I think these should be handled by the MVC validation only; I'm only concerned about more complex validations.

like image 650
JMM Avatar asked Jun 29 '10 13:06

JMM


People also ask

Should validation be done in controller or service?

As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place. Save this answer.

Why we use service layer in MVC?

A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic. For example, the product service layer in Listing 3 has a CreateProduct() method.

How do you write a validation controller?

The first step to enable validation in a controller is to add @Valid to a method parameter that is created using model binding. In lieu of explicit validation error handling (which we will cover below), Spring Boot throws an exception if validation fails for the new object.


1 Answers

Don't duplicate code. Use JSR303 Bean Validation so you can use the same validation logic in all layers of your app.

Hibernate Validator (a separate project from the Hibernate ORM stuff) provides the reference implementation of this interface. It is dead simple to use, you can get started with it very quickly.

like image 108
matt b Avatar answered Sep 17 '22 23:09

matt b