Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Place for Validation in Model/View/Controller Model?

I am working on a PHP project which makes extensive use of the MVC design pattern. I am looking to add validation to a form and am curious as to what the right place for validation is.

Due to the way that forms are generated, validation on postback data is a lot simpler and less repetitive in view components. Is it acceptable to have the view validating response data, or should this be implemented within the controller, or even the model?

What are the benefits?

like image 283
Lea Hayes Avatar asked Mar 14 '11 23:03

Lea Hayes


People also ask

How do you validate a controller model?

Using “DisplayFormat” you can specify the data format that should be displayed. For example, display date, currency, etc. Here, instead of displaying null, you can display anonymous. Now create a controller and a view to apply those validations.

How do you handle validation in MVC?

In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code.

Should I validate 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.


1 Answers

The right place for validation is the Model.

This makes most sense because you are doing validation on the data, which is what the model represents. In terms of the CRUD updates, the model should always be used somehow.

  • If you are changing data from the view, you should have validations being checked.

  • If you have controllers changing data, you should have validations being checked.

  • And finally if you have having the model itself changing data, you should still have validations.

The only way to achieve this state is to have the validation go into the model.

Due to performance and faster response, after implementing the validations in the model, you should try to add some sort of client side(JS) to immediately notify the end user.

Validation is always about the data. Why are you validating data? So you can keep the integrity of the information your storing. Having the validations at the model level allows data to theoretically be always correct. This is always a neccesity. From there you can add extra validations in your business logic and client side to make your application more user friendly.

like image 188
Mike Lewis Avatar answered Oct 16 '22 03:10

Mike Lewis