Custom validation -Check the max words

Monday, 3 February 2014

Custom Validation -Check the Max words


Controller:

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

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


Model:

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(2, ErrorMessage = "Too many words in {0}")]
        public string Address { get; set; }

    }
}


Model[CustomValidation ]
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;
        }
    }
}


View:


@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")
}



ScreenShot:






Conclusion:

  If user can specify greater than two words in the Address field,the display the Validation Message.