Oguz Bilgic
Oguz Bilgic

Reputation: 3480

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.

Upvotes: 5

Views: 1559

Answers (4)

BalusC
BalusC

Reputation: 1108557

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.

Upvotes: 2

Paul Creasey
Paul Creasey

Reputation: 28824

validation should be performed in both the model and the view in my opinion.

Upvotes: 1

Galen
Galen

Reputation: 30170

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

Upvotes: 1

stimms
stimms

Reputation: 44046

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.

Upvotes: 7

Related Questions