New Validation Attributes in ASP.NET MVC 3 Future

Posted by imran_ku07 on ASP.net Weblogs See other posts from ASP.net Weblogs or by imran_ku07
Published on Sat, 05 Feb 2011 11:22:00 GMT Indexed on 2011/02/05 15:26 UTC
Read the original article Hit count: 602

     Introduction:

 

          Validating user inputs is an very important step in collecting information from users because it helps you to prevent errors during processing data. Incomplete or improperly formatted user inputs will create lot of problems for your application. Fortunately, ASP.NET MVC 3 makes it very easy to validate most common input validations. ASP.NET MVC 3 includes Required, StringLength, Range, RegularExpression, Compare and Remote validation attributes for common input validation scenarios. These validation attributes validates most of your user inputs but still validation for Email, File Extension, Credit Card, URL, etc are missing. Fortunately, some of these validation attributes are available in ASP.NET MVC 3 Future. In this article, I will show you how to leverage Email, Url, CreditCard and FileExtensions validation attributes(which are available in ASP.NET MVC 3 Future) in ASP.NET MVC 3 application.

 

    Description:

 

          First of all you need to download ASP.NET MVC 3 RTM Source Code from here. Then extract all files in a folder. Then open MvcFutures project from mvc3-rtm-sources\mvc3\src\MvcFutures folder. Build the project. In case, if you get compile time error(s) then simply remove the reference of System.Web.WebPages and System.Web.Mvc assemblies and add the reference of System.Web.WebPages and System.Web.Mvc 3 assemblies again but from the .NET tab and then build the project again, it will create a Microsoft.Web.Mvc assembly inside mvc3-rtm-sources\mvc3\src\MvcFutures\obj\Debug folder. Now we can use Microsoft.Web.Mvc assembly inside our application.

 

          Create a new ASP.NET MVC 3 application. For demonstration purpose, I will create a dummy model UserInformation. So create a new class file UserInformation.cs inside Model folder and add the following code,

 

    public class UserInformation
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [Url]
        public string Website { get; set; }

        [Required]
        [CreditCard]
        public string CreditCard { get; set; }

        [Required]
        [FileExtensions(Extensions = "jpg,jpeg")]
        public string Image { get; set; }
    }

 

          Inside UserInformation class, I am using Email, Url, CreditCard and FileExtensions validation attributes which are defined in Microsoft.Web.Mvc assembly. By default FileExtensionsAttribute allows png, jpg, jpeg and gif extensions. You can override this by using Extensions property of FileExtensionsAttribute class.

 

          Then just open(or create) HomeController.cs file and add the following code,

 

    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(UserInformation u)
        {
            return View();
        }

    }

 

          Next just open(or create) Index view for Home controller and add the following code,

 

@model NewValidationAttributesinASPNETMVC3Future.Model.UserInformation

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

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

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>UserInformation</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Website)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Website)
            @Html.ValidationMessageFor(model => model.Website)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CreditCard)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CreditCard)
            @Html.ValidationMessageFor(model => model.CreditCard)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Image)
            @Html.ValidationMessageFor(model => model.Image)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

 

          Now just run your application. You will find that both client side and server side validation for the above validation attributes works smoothly. 

 

           

 

    Summary:

 

          Email, URL, Credit Card and File Extension input validations are very common. In this article, I showed you how you can validate these input validations into your application. I explained this with an example. I am also attaching a sample application which also includes Microsoft.Web.Mvc.dll. So you can add a reference of Microsoft.Web.Mvc assembly directly instead of doing any manual work. Hope you will enjoy this article too.

 

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about ASP.NET MVC