In this article will create a simple ASP.NET MVC Project.
Contents
Introduction
Step 37:- Add Validation namespace
Step 38 :- Decorate your property
Step 39 :- Display error on the UI
Step 40 :- Run the project for output
Conclusion :
In the previous two parts of the article we created a simple application with insert , update and delete. Any software application in this world is not complete with out validations.
If you see our project currently you can enter empty fields and new record with empty data gets created. In this article we will make an attempt to Add Validations on our form and make sure that Validation checks occurs before making a new record in Database.
Validation can be done on client side as well as server side. In this article we will focus on server side validation.Server Side validations can be implemented by using Data Annotations.
Data Annotations is a ready made component in .NET and it exists inside System.ComponentModel.DataAnnotations namespace. In case you are new to data annotations we would suggest you to watch the below video on C# Data annotation. Please note data annotation is part of .NET and not of MVC. MVC uses .NET data annotation library.
It very handy to use and execute, developersdonot need to write big logics for Validation. We just need to decorate the property name in a square brackets like [validationtype] and the validation magic just happens.
To use Data Annotations we will have to use its name space, so lets add this line at the top of University model file which is University.cs. In case you do not have data annotation in your references please add reference the same in your project.
usingSystem.ComponentModel.DataAnnotations;
Once the name space is imported now we can use all the Validation Types of Data Annotations. It has total 43 (Forty Three) Validations among them the most commonly used are :
Credit Card, Display , Email Address, Key , Max length , Min Length, Phone , Range , Regular Exp , Required and StringLength.
We will demo few from the above in this project. Now decorate the properties with the Validation Types for which you need the validation to happen during the form submission.
Make changes to “University.cs” file :
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.ComponentModel.DataAnnotations; //Using the namespace for Validation
namespaceMyApp.Models
{
publicclassUniversity
{
[Key] // Declares as a Primary Key which auto increments
publicint ID { get; set; }go
[Required(ErrorMessage="Please Enter Registration No")] // Reg No is a required field now
[RegularExpression("^[a-zA-Z]{2,2}[0-9]{3,3}$",ErrorMessage="Only Accept a regular pattern like AB123 ")]// Only Accept a regular pattern like "AB123"
publicstringRegNo { get; set; }
[Required(ErrorMessage = "Please Enter University Name")] //Name is a required field now.
[StringLength(8, ErrorMessage = "Maximum Length Can be 8")] // Name can be of maximum length 8
publicstring Name { get; set; }
[Required(ErrorMessage = "Please Enter University City")] // City is a required field now.
[Display(Name = "University City")] //Display City as University City in UI
publicstring City { get; set; } // City
}
}
Now we have decorated the Validations in Model Class we would love to see the validation error on displayed on our page.
Here we will be using HTML helper class and the method will be ValidationMessage() with the parameter as the field name. The below changes is done in “AddUniversity.cshtml”
Registration No : <inputtype="text"name="RegNo">@Html.ValidationMessage("RegNo")
<br/><br/>
University Name : <inputtype="text"name="Name">@Html.ValidationMessage("Name")
<br/><br/>
City :<inputtype="text"name="City">@Html.ValidationMessage("City")
<br/><br/>
So the error message for that field is displayed just opposite to the Field Name at the end.
Let’s execute the project and check the Validations for the FORM.
- Filling invalid Registration No
- Entering correct pattern for Registration No.
- Validating University Name
- Entering Name with maximum length 8
- Entering all the fields correct
We can see that the Validation is being checked at the Server Side for all the fields with the given Validation Types using Data Annotations, but how the model validation is connected to the Controller Actions. For each action we are using ModelState for Model Binding which uses IsValid property i.e.ModelState.IsValid inside our Action methods. This is the point where it invokes all Validation for the particular Form and then the further part of the method is executed
We have implemented Validation in the above form. I hope you will be able to demo the same from your side. I would also suggest you to try other Validations of Data Annotations.
Thank You for reading this article and giving your worth time..!