Data Validation in MVC

3.5k views Asked by At

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

3

There are 3 answers

0
Sudhir Bastakoti On

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.

0
eppdog On

My suggestion would be to validate in the view with some form of validation binding, and then again in the model before persisting to any data store.

0
drogon On

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.