Wednesday, 1 January 2014

MVC Tips : Custom Annotation validation in ASP.Net MVC 4

Click Here to Download CustomAnnotationInMVC.zip Example.

You can write your own custom annotations in MVC 4.
Here we can do custom validation using custom annotations. Custom annotations validation derive from the ValidationAttribute base class. This base class available in 'System.ComponentModel.DataAnnotations' namespace. ValidationAttribute class is abstract class.

For custom validation you need to write your own class and inherit ValidationAttribute class. After that, you need to override IsValid Method. IsValid Method has two parameters 'Value' and 'ValidationContext'.

  • Value : Which contains your data, which is going to validate.
  • ValidationContext : This parameter is very important. This content information like model object instance, model type friendly display name and other information
In this method you write your own logic for validate data and return result. If value is validate at that time you need to return this 'ValidationResult.Success' else you return result like 'return new ValidationResult(your custom error message)'

Here is example for this.

In this example we create one MaxWords Custom Validation. This custom validation raise validation error if string contains words more than specified word count.

You can see in this example, we used 'MaxWords' custom attribute on 'Address' field. If address field contains more than 5 words at that time validator raise error.
Here, in this, we can set custom error message as well. You can pass your error message. If you did not pass any error message in that case we also set default error message in which we replace your column display name at appropriate place. You can see all these things in code.

MaxWordsAttribute.cs : 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CustomAnnotationInMVC
{
    public class MaxWordsAttribute : ValidationAttribute
    {
        private readonly int _maxWords;

        public MaxWordsAttribute(int maxWords):base("{0} more words than require.")
        {
            _maxWords = maxWords;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var strValue = value.ToString();
                if (strValue.Split(' ').Length > _maxWords)
                {
                    string strErrorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(strErrorMessage);
                }
            }
            return ValidationResult.Success;
        }
    }
}

customer.cs : 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace CustomAnnotationInMVC.Models
{
    public class Customer
    {
        [Required]
        public string Name{ get; set; }

        [Required]
        [Display(Name="Address")]
        [MaxWords(10,ErrorMessage="Too many words in {0}")]
        public string Address{ get; set; }

    }
}

HomeController.cs : 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomAnnotationInMVC.Models;

namespace CustomAnnotationInMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

        [HttpPost]
        public ActionResult Add(Customer obj  )
        {
            return View();
        }

    }
}

View (Add.chtml) : 
 
@model CustomAnnotationInMVC.Models.Customer

@{
    ViewBag.Title = "Add";
}

<h2>Add</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Customer</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,"", new { style="color:red"})
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Address)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Address)
                @Html.ValidationMessageFor(model => model.Address,"", new { style="color:red"})
            </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Output :


Below are the books that you would like :

No comments:

Post a Comment