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 :

9 comments:

  1. check http://mvc4all.com for some more details on MVC topics

    ReplyDelete
  2. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.

    AWS Online Training | Online AWS Certification Course - Gangboard
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR
    AWS Training in Bangalore |Best AWS Training Institute in BTM ,Marathahalli

    ReplyDelete
  3. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.

    angularjs Training in chennai
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  4. From your discussion I have understood that which will be better for me and which is easy to use. Really, I have liked your brilliant discussion. I will comThis is great helping material for every one visitor. You have done a great responsible person. i want to say thanks owner of this blog.
    python training in tambaram | python training in annanagar | python training in jayanagar

    ReplyDelete
  5. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Online DevOps Certification Course - Gangboard
    Best Devops Training institute in Chennai

    ReplyDelete
  6. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in velachery| rpa training in tambaram |rpa training in sholinganallur | rpa training in annanagar| rpa training in kalyannagar

    ReplyDelete
  7. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    Java training in Tambaram | Java training in Velachery

    Java training in Omr | Oracle training in Chennai

    ReplyDelete
  8. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete