Thursday, June 18, 2015

Conditional Model validation in MVC

When we use “IsValid”  property of ModelState, it validate all property of model and summarize the error. If there is use case, where we would like to validate model property individually or we will validate if property is present in form collection.

ModelStateDictionary class provides IsValidField() function which takes property name as argument and returns Boolean as validation result.

Here is sample implementation to validate certain property if it is present in FormCollection.

   public class Employee
    {
        [MinLength(3 , ErrorMessage="minimum 3")]
        public string EmpID { get; set; }

        [MaxLength(3 , ErrorMessage = "maximum 3")]
        public string EmpCode { get; set; }
    }

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Save(Employee p , FormCollection Collection)
        {
            string[] keys = Collection.AllKeys;
            Boolean IsValid = true;

            foreach (var item in keys)
            {
                if (ModelState.IsValidField(item) == false)
                {
                    IsValid = false;
                    break;
                }
            }
            if (IsValid == false)
            {
               var errors = ModelState.Values.SelectMany(v => v.Errors);
               return View("Index", p);
            }
            else
            {
                return View("Index");
            }
        }


    }

Here is view

         <form action="../Home/Save" method="post">
             @Html.ValidationSummary()
            <input type="text" name ="EmpID" value="1" />
            <input type="text" name ="EmpCode" value="123411" />
           
            <input type="submit" name="btnSubmit" value="submit" />
        </form>


We are seeing error message based on availability of property.


No comments:

Post a Comment