Home > DeveloperSection > Articles > Validation in ASP.NET MVC3

Validation in ASP.NET MVC3


ASP.NET MVC ASP.NET MVC 
Ratings:
1 Comment(s)
 9233  View(s)
Rate this:

Validation in ASP.NET MVC3

In my last article I told you that how to create first program in ASP.NET MVC3 using Razor framework. If you are new comers for MVC3 then you can start creating your first MVC3 program by following this link First ASP.NET MVC3 Application . Here you will get some basics of ASP.NET MVC3 and you have feel easy to learn it.

In this article I am going to tell you that how to implement validation in asp.net mvc3. Here I will show you step by step to create program on validation in ASP.NET MVC3.

As we know that every web application has required some type of validation to check data correctness and preventing sql injection etc. In ASP.NET Web Forms we have to implement validation on client side as well as server side which is very complicated for large application. But ASP.NET MVC has improvements on it, now we don’t need to implement validation on both sides. We can write code in one place (i.e. server side) using c# and use it in both places.

In ASP.NET MVC we can use Data Annotation to implement validation which can be found in two namespaces: System.Web.Mvc and System.ComponentModel.DataAnotation. Following types of validation is available in ASP.NET MVC3.

1)      Remote Validation: Remote validation is used to check whether particular value exists or not on server side, without posting form. Suppose, you are creating a registration form and now you want to check that particular user name is available or not for registration. Then for this purpose you can use Remote Validation. Here I am providing a code snippet to implement remote validation on user name field.

[DataType(DataType.Text)]

[Display(Name = "User Name")]

[Remote("IsUserNameAvailable", "Employee")]

[Required(AllowEmptyStrings = false, ErrorMessage = "User Name field cannot be empty!")]

[StringLength(20, MinimumLength = 6, ErrorMessage = "User Name must have minimum 6 and maximum 20 character!")]

public string UserName { get; set; }

 

                Here you can see highlighted text. When are you using remote validation which I had specify in Model accept two parameters, first one is View method and another one in controller name. Below I am giving you view method code which is used for remote validation.

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]

        public JsonResult IsUserNameAvailable(string UserName)

        {

            List<string> lstUserName = new List<string>();

            lstUserName.Add("Awadhendra"); lstUserName.Add("John"); lstUserName.Add("Haider");

            if (lstUserName.Contains(UserName))

                return Json(true, JsonRequestBehavior.AllowGet);

            return Json("User is available", JsonRequestBehavior.AllowGet);

        }

 

Here I had used JSON binding technique to bind result of validation. If you will see code carefully, you find that I used an attribute called OutputCache in which I have specified that no to maintain or store any data in cache. Cache is a feature of ASP.NET/MVC web application to improve response time. Here I have created a list of user name. If user name is available in list then no message is displayed otherwise if user name is available for registration then a message displayed user name is available.

2)      Required: We can use required data annotation attribute to mark field as required. Any field which is marked by required attribute then it must have value when submitted to server.

3)      Compare: Whenever you want to compare values of two fields; for example Password and Confirm Password then you can use Compare attribute.

4)      StringLength: You can use StringLength attribute to decide length of value in field.

 

Similarly you can use RegularExpression validation for validating some values on the basis of regular expression such as validates Email Address or Age. I will show you example of Regular expression later.

For creating this demo firstly create a Model class named Employee in your ASP.NET MVC3 project and write down following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ComponentModel.DataAnnotations;

using System.Web.Mvc;

 

namespace RemoteValidation.Models

{

    public class Employee

    {

 

        [DataType(DataType.Text)]

        [Display(Name = "User Name")]

        [Remote("IsUserNameAvailable", "Employee")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "User Name field cannot be empty!")]

        [StringLength(20, MinimumLength = 6, ErrorMessage = "User Name must have minimum 6 and maximum 20 character!")]

        public string UserName { get; set; }

 

        [DataType(DataType.Password)]

        [Display(Name = "Password")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "Password field cannot be empty!")]

        [StringLength(20, MinimumLength = 6, ErrorMessage = "Password must have minimum 6 and maximum 20 character!")]

        public string Password { get; set; }

 

        [DataType(DataType.Password)]

        [Display(Name = "Confirm Password")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password field cannot be empty!")]

        [Compare("Password", ErrorMessage = "Password and confirm password must be same!")]

        public string ConfirmPassword { get; set; }

 

        [DataType(DataType.EmailAddress)]

        [Display(Name = "Email")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "Email address field cannot be empty!")]

        //[RegularExpression("",ErrorMessage="You did not enterd correct email address.")]

        public string Email { get; set; }

 

        [Display(Name = "Gender")]

        [Required(ErrorMessage = "You did not select your gender!")]

        public bool Gender { get; set; }

 

    }

}

 

 

After creating Model, add controller named Employee in Controller directory and right down following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using RemoteValidation.Models;

using System.Web.UI;

 

namespace RemoteValidation.Controllers

{

    public class EmployeeController : Controller

    {

        [HttpGet]

        public ActionResult RegisterEmployee()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult RegisterEmployee(Employee empModel)

        {

            if (ModelState.IsValid)

            {

                //If record is valid then call thanks page or any other page

            }

            else

                ModelState.AddModelError("Error", "Please correct all errors");

            return View();

        }

 

        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]

        public JsonResult IsUserNameAvailable(string UserName)

        {

            List<string> lstUserName = new List<string>();

            lstUserName.Add("Awadhendra"); lstUserName.Add("John"); lstUserName.Add("Haider");

            if (lstUserName.Contains(UserName))

                return Json(true, JsonRequestBehavior.AllowGet);

            return Json("User is available", JsonRequestBehavior.AllowGet);

        }

    }

}

 

 

Now you have been successfully created Model and Controller. Now it’s time to add view in your MVC project. Create a strongly typed view named RegisterEmployee and right down following code.

@model RemoteValidation.Models.Employee

@{

    View.Title = "RegisterEmployee";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

<fieldset>

    <legend>New Employee Registration Page</legend>

    @using (@Html.BeginForm())

    {

        <div class="editor-label">

            @Html.LabelFor(m => m.UserName)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName)

        </div>

        <div class="editor-lable">

            @Html.LabelFor(m => m.Password)

        </div>

        <div class="editor-field">

            @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password)

        </div>

        <div class="editor-label">

            @Html.LabelFor(m => m.ConfirmPassword)

        </div>

        <div class="editor=field">

            @Html.PasswordFor(m => m.ConfirmPassword) @Html.ValidationMessageFor(m => m.ConfirmPassword)

        </div>

        <div class="editor-lable">

            @Html.LabelFor(m => m.Email)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(m => m.Email, new { type = "email" }) @Html.ValidationMessageFor(m => m.Email)

        </div>

        <div class="editor-label">

            @Html.LabelFor(m => m.Gender)

        </div>

        <div class="editor-field">

            @Html.RadioButtonFor(m => m.Gender, false) Male @Html.RadioButtonFor(m => m.Gender, false)

            FeMale @Html.ValidationMessageFor(m => m.Gender)

        </div>

       

        <div style="margin-top: 20px; margin-bottom: 20px;">

            <input type="reset" value="Reset" />

            &nbsp;&nbsp;

            <input type="submit" value="Register" />

        </div>

    }

</fieldset>

 

 

Now, you have done almost all things except one thing. Right now validations which have you implemented are working but it did not work at client side. For implementing this validation on client side you need to add following jquery file in _Layout.cshtml view which you can find in shared directory.

<script src="@Url.Content("~/Scripts/jquery-1.4.1.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

 

It might be possible that these jquery files are already on there but in commented form then you need to uncomment it. After performing this task you have successfully creating this exercise.

Thanks.


Validation in ASP.NET MVC3

By James Smith on   4 years ago

Great Job Awadhendra!

It's really helpful for implementing validation in my website.


Don't want to miss updates? Please click the below button!

Follow MindStick