Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does input validation happen in MVC?

Ok, this has probably been asked before but i cant find a definative answer. Where in the MVC pattern should validation of input happen?

I would like to say that things like empty fields and basic general validation should happen in the controller and that rules as lengths and valid characters of for example usernames / passwords etc should happen at the model layer.

However, this means spreading this burdon around the application which surely cant be good either?

Sorry if this question is naieve but I am relatively new to this type of programming and want to get things correct from the start.

like image 537
david Avatar asked Oct 10 '10 20:10

david


People also ask

Where should input validation occur?

Because it is difficult to detect a malicious user who is trying to attack software, applications should check and validate all input entered into a system. Input validation should occur when data is received from an external party, especially if the data is from untrusted sources.

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.

Which namespace is required for validating the input data in MVC?

DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.


1 Answers

Validation is the job of the model.

As models have various attributes (fields), only the 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.

Your model should encapsulate this logic so you can interrogate it ("are you valid?") and not have it spread across other parts of your code.

like image 81
Andrew Vit Avatar answered Nov 15 '22 13:11

Andrew Vit