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

AnnotationsDescription
RequiredIt is used to make a required field.
DisplayNameIt is used to define the text we want to display for the fields.
StringLengthIt defines a maximum length for a string field.
RangeIt is used to set a maximum and minimum value for a numeric field.
BindIt lists fields to exclude or include when binding parameter or form values to model properties.
ScaffoldColumnIt allows hiding fields from editor forms.
MaxLengthIt is used to set max length for a field.
EmailAddressIt is used to validate email address.
DataTypeIt is used to specify data type for the field.
RegularExpressionIt 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




Latest Courses