Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation Layer in MVC pattern

Where is the best place to validate data which will be used by model. For example, think about registration form. We have some data which come from registration form. So where is the best place to verify this data.We should check every data by if statements or special validator class, and this means lots of coding, so i want to learn where is the place to do this.

In Controller? or Model?

Both? Because some of the data should be validated by other models?

If you are not sure about exact answer, please try to find possible advantages and disadvantages of both ways.

like image 818
Oguz Bilgic Avatar asked Dec 12 '09 21:12

Oguz Bilgic


People also ask

What is MVC validation?

Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.

How is validation done in MVC?

Validation is carried out using the jQuery Validation library. Generally, in webform based applications, we make use of JavaScript in order to do client side validations. In MVC, client side validation do not introduce any JavaScript in the code to carry out validation.

Should validation be done in controller?

If you're validating data on server side, And your validation does not require application business logic (i.e you're not checking to see if the user has enough credit in his account), You should validate in the controller.


3 Answers

The source of the validation data should be in the model while the actual checking should probably be done at both the view level (perhaps with javascript or UI hints) and at the model level. Purists will suggest that the view should not be involved but I disagree.

like image 107
stimms Avatar answered Sep 27 '22 21:09

stimms


Certainly not in the controller, its sole task should be just controlling the request/response and familarize model and view with each other. Do it in the business model. Not with a bunch of if-statements, but just using a for-loop and an abstract validation framework.

Validation in the view should only be done to improve user experience. In webapps the view is basically the HTML page. In that validation is only possible with Javascript which runs entirely at the client side. The client has full control over it, such as hacking/disabling it. Use JS validation only to improve user experience (i.e. quicker response, no flash of content). Still do the (same) validation in the server side for better robustness.

like image 42
BalusC Avatar answered Sep 27 '22 22:09

BalusC


Putting validation in your models prevents you from having to repeat validation code in a bunch of controllers.

like image 27
Galen Avatar answered Sep 27 '22 22:09

Galen