Javatpoint Logo
Javatpoint Logo

ASP.NET MVC Input Validation

Validation of user input is necessary task for the application programmer. An application should allow only valid user input so that we get only desired information.

ASP.NET MVC framework provides built-in annotations that we can apply on Model properties. It validates input and display appropriate message to the user.


Commonly used Validation Annotations

Annotations Description
Required It is used to make a required field.
DisplayName It is used to define the text we want to display for the fields.
StringLength It defines a maximum length for a string field.
Range It is used to set a maximum and minimum value for a numeric field.
Bind It lists fields to exclude or include when binding parameter or form values to model properties.
ScaffoldColumn It allows hiding fields from editor forms.
MaxLength It is used to set max length for a field.
EmailAddress It is used to validate email address.
DataType It is used to specify data type for the field.
RegularExpression It is used to associate regular expression for a field.

Example

Let's create an example that will validate input by using the annotations. To create the example, first we are creating a StudentsController and then a Student Model.

Controller

// StudentsController.cs


Model

// Student.cs


View

// Index.cshtml

Output:

To see the output, right click on the Index.cshtml file and select view in browser. This will produce the following result.

ASP Validation 1

As we can see that it validates form fields and display error message to the user. In the below screenshot, we are validating that the entered data is as expected.

ASP Validation 2




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA