Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Does the Model or Controller validate user input

What part in the MVC does user input get validated? For example, user registration system, the user inputs data in the View, where does the user's input get cleaned and validated for the correct input, eg. correct email, applying php cleaning functions..would this happen in the controller or the model? and which would decide what errors are returned

thanks

like image 923
dre1080 Avatar asked Oct 04 '10 02:10

dre1080


People also ask

What is validate input in MVC?

The ValidateInput attribute is used to allow sending the HTML content or codes to the server which, by default, is disabled by ASP.NET MVC to avoid XSS (Cross-Site Scripting) attacks. This attribute is used to enable or disable the request validation. By default, request validation is enabled in ASP.NET MVC.

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 controller validate data?

Validation is to maintain data integrity, not to check user input. All model attributes should be validated every time before it is saved, not only when it is created, not only test some attributes from a form. Manipulating model in controllers, services etc should not bypass the validation.


2 Answers

As per the classic MVC model (graphical apps), user input is a model too. Most PHP framweworks follow the Passive-MVC or MVC-2 model, where it's the domain of the controller or controller helpers. Do what looks most maintainable.

like image 186
mario Avatar answered Oct 16 '22 01:10

mario


In my opinion, it all depends on what kind of validation you want to perform:
1. If you don't want a field to be empty or be in a specific format, I will do that check on the view layer. This is where most regex could be applied.Only once the user input is valid, is then that I will pass control to the controller for further business logic processing
2. If I want to ensure that a user input(, say a username) is unique or not , I will do that validation on the controller side and pass any feeback back to the view. In the latter, the controller might have a dependency on an abstraction of a data access layer or service layer or any other controller helpers.
3. Still have to rationalize on the approach to use.

like image 20
walters Avatar answered Oct 16 '22 01:10

walters