Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Validation in MVC

Suppose i have a 'View' for filling up form for renting a DVD , as per MVC architecture , either of 'Controller' or 'Model', who is supposed to validate the form data? Thanks

like image 887
Ravi Jain Avatar asked Oct 09 '22 19:10

Ravi Jain


2 Answers

You validation should be in Model section of MVC. As models have various fields, only models can know what combination of inputs make that model valid. It's not just about whether a field is blank, or the input of that field matches some pattern, but sometimes this is a combination of field inputs, or the model's relationship to other models that determine the valid state.

like image 131
Sudhir Bastakoti Avatar answered Oct 12 '22 10:10

Sudhir Bastakoti


All 3 are usually involved in the validation process if you follow the typical flow.

The model defines validation attributes such as the required or stringlength attributes. The controller checks the validation state of the model via ModelState.IsValid and makes decisions accordingly. The view may additional provide client-side validation for those same attributes. Don't rely solely on js to validate the form.

like image 39
drogon Avatar answered Oct 12 '22 11:10

drogon