Create a simple ASP.NET MVC Project (Part 3) Validations

Panthmadan
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 3210 red flag
Rating: 4 out of 5  
 1 vote(s)

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 :

Introduction

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.

Step 37:- Add Validation namespace

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;

Step 38 :- Decorate your property

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

    }
}

Step 39 :- Display error on the UI

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.

Step 40 :- Run the project for output

Let’s execute the project and check the Validations for the FORM.

  • Submitting Empty 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

Conclusion :

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..!

Page copy protected against web site content infringement by Copyscape

About the Author

Panthmadan
Full Name: Madan Panth
Member Level: Starter
Member Status: Member,MVP
Member Since: 12/15/2015 4:34:44 AM
Country: India

www.questpond.com
Learn MVC in 16 hours
Learn design pattern in 8 hours
Learn C# in 100 hours series
Learn MSBI in 32 hours
Learn SharePoint Step by Step in 8 hours

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)