Friday, 18 April 2014

How to create Custom Data Annotations using MVC 4 application with client validation

How to create Custom Data Annotations using MVC 4 application with client validation



Step 1 : create mvc application .

Step 2 : Add one entity class "Employee"

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        public int Age { get; set; }

         public string Sem { get; set; }

        public string EmailAddress { get; set; }

        public int Year { get; set; }

    }

Step 3 : Create .cshtml file of Employee creation.

Step 4 : Add one class file of creation of CustomValidationAttribute

Step 5 : Paste below code in that file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace MVC_Custom_DataAnnotations
{
    public class CustomRangeAttribute : RangeAttribute, IClientValidatable
    {
        private double _Minimum;
        private double _Maximum;
        private string _message;
        public CustomRangeAttribute(double minimum, double maximum, string message)
            : base(minimum, maximum)
        {
            _Minimum = minimum;
            _Maximum = maximum;
            _message = message;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            double valueObject;
            Double.TryParse(Convert.ToString(value), out  valueObject);
            return _Minimum <= valueObject && valueObject <= _Maximum;
        }

        public override string FormatErrorMessage(string name)
        {
            return _message;
        }


        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("range", string.Format("{0}~{1}", Minimum, Maximum));
            rule.ValidationType = "customrange";
            yield return rule;
        }
    }

    public class CustomStringLengthAttribute : StringLengthAttribute, IClientValidatable
    {
        public int MaximumLength;
        public string message;
        public string KeyName;

        public CustomStringLengthAttribute(int maximumLength, string errormessage)
            : base(maximumLength)
        {
            MaximumLength = maximumLength;
            message = errormessage;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            int valueObject = Convert.ToString(value).Length;
            return valueObject <= MaximumLength;
        }
        public override string FormatErrorMessage(string name)
        {
            return message;
        }
       

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("maximumlength", MaximumLength);
            rule.ValidationType = "customstringlength";
            yield return rule;
        }
    }

    public class CustomRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        private string Pattern;
        private string message;

        public CustomRegularExpressionAttribute(string pattern, string errorMessage)
            : base(pattern)
        {
            Pattern = pattern;
            message = errorMessage;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            Match match = Regex.Match(Convert.ToString(value), Pattern, RegexOptions.IgnoreCase);

            return match.Success;
        }

        public override string FormatErrorMessage(string name)
        {
            return message;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("pattern", Pattern);
            rule.ValidationType = "customregularexpression";
            yield return rule;
        }
    }
}

Step 6 : Now add attribute to Employee class object.

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        [CustomRangeAttribute(1, 100, "Age between 1 to 100")]
        public int Age { get; set; }

        [CustomStringLengthAttribute(5, "Maximum char allowed in sem field is 5.")]
        [DataMember]
        public string Sem { get; set; }

        [CustomRegularExpressionAttribute("^[A-Za-z0-9_\\+-]+(\\.[A-Za-z0-9_\\+-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*\\.([A-Za-z]{2,4})$", "Please enter valid email address.")]
        public string EmailAddress { get; set; }

        [CustomRangeAttribute(1950, 2014, "Year between 1950 to 2014")]
        public int Year { get; set; }

    }

Step 8 : Add code for checking server side validation.

 [HttpPost]
        public ActionResult Create(Employee  emp)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View(emp);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

Step 9 : Run your application and try to produce the error using invalid value.

Step 10 : This way you can create custom validation for server side.

Watch video for visual explanation on this point.

https://www.youtube.com/watch?v=-t1EemDasMc&feature=youtu.be