Thursday, June 18, 2015

Custom model validation in MVC

It is another extension point of MVC. In need we can implement ValidationAttribute class in our custom class and implement model validation logic there.

Let’s explain one use case to implement sample example. For example, we have one Employee class like this

public class Employee
    {
        [CombinedLengthChecking(3, "EmpID", "EmpCode")]
        public string EmpID { get; set; }

        public string EmpCode { get; set; }
    }

And the total length of EmpID and EmpCode should 6 and each one must contain length 3. This validation logic we will implement in “CombinedLengthChecking” class.

public class CombinedLengthChecking : ValidationAttribute
    {
        public CombinedLengthChecking(int minLength, params string[] propertyNames)
        {
            this.PropertyNames = propertyNames;
            this.MinLength = minLength;
        }

        public string[] PropertyNames { get; private set; }
        public int MinLength { get; private set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
           
            var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();

            var totalLength = values.Sum(x => x.Length);
            if (this.MinLength < 3)
            {
                return new ValidationResult("Length sould more than 3");
            }
            if (totalLength > 6)
            {
                return new ValidationResult("Error in Validation");
            }
            return null;
        }
    }


Here is our code in Controller.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public void Save(Employee p)
        {

            Boolean value = ModelState.IsValid;
        }


    }


Once we run the application, we will see that the execution flow has reached in error block .



<form action="../Home/Save" method="post">
            <input type="text" name ="EmpID" value="123" />
            <input type="text" name ="EmpCode" value="1234" />
            <input type="submit" name="btnSubmit" value="submit" />
        </form>

No comments:

Post a Comment