Please briefly explain me about validation in MVC with example and also with suitable image.
What is validation in MVC?
393
27-Jan-2020
Updated on 27-Jan-2020
Nishi Tiwari
27-Jan-2020In the web applications, domain validation plays an important role in the application. Data entered from the client’s side may not always be correct. Therefore we need to ensure that the data entered by the user is not only validated but it is also correct application-logic wise.
In the ASP.NET Model validations three type of validations we can perform:
1. HTML validation / JavaScript validation
2. ASP.NET MVC Model validation
3. Database validation
But the above all most secure validation is the ASP.NET MVC model validation. In HTML/JavaScript, the validation can be break easily, but the model validation cannot. In ASP.NET MVC model validations are done using Data Annotation and it is inherited from System.ComponentModel.DataAnnotations assembly.
We can also say that for any website, there are many input fields. Users can enter the data in those input fields. Now these input fields are exposed to the client browser. Users may enter anything they wants to the input fields. If the user may enters some wrong data then you will have some irrelevant or wrong data with your database also. In this way, providing the authority to the user to enter data in input fields which we will be inserting into the database and which will be used for many purposes can cause security holes in to the system if we don't put any restrictions on the input fields.
In simple words we can say that validations are rules set by the developer on input fields so as to satisfy the business rules for those particular input field in which they have the proper data in the system.
There are two types of validations:
1. Server side Validations
2. Client Side Validations
While performing validations we must need to take care of not only the proper validation, but also ensure the validation meets the business rule as per the requirement. This also reduces the amount of code we need to write and makes the code to write less error prone and easier to maintain.
ASP.NET MVC framework provides the built-in annotations which we can apply on Model properties. It validates input first and then display appropriate message to the user.
Commonly used Validation Annotations
Required:- It is used to make a required field.
DisplayName:- It is used to define those text which we want to display for the fields.
StringLength:- It defines a maximum length for a string field which is needed.
Range:- It is used to set a maximum and minimum value for a numeric field.
Example
Create an example which will validate input by using the annotations. We are creating a StudentsController and then a Student Model.
Controller
Model
View
Output:
To see an output, right click on the Index.cshtml file and select view in browser. This will produce the following output.