Monday, March 04, 2013

mvc 4 custom server validation on multiple fields

Imaging there is a many to many relationship between category and product and there are some specific information required on this many to many relationship, therefore we need a dedicated entity CategoryProduct to work with. On submission I need to validate whether the combination of category and product selections already exist.

in validation controller provide:


public JsonResult ValidateCategoryProduct(int? categoryProductId, int categoryId, int productId)
        {
            if (!categoryProductId.HasValue)
            {
                categoryProductId = -1;
            }

            var validationResult = categoryProductRepository.ValidateCategoryProduct(categoryProductId.Value, categoryId, productId);
            if (validationResult)
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                string output = "This category product relationship has already been setup.";
                return Json(output, JsonRequestBehavior.AllowGet);
            }
        }

in my model I have


[DisplayName("CategoryId")]
        [Remote("ValidateCategoryProduct", "ValidationLogic", AdditionalFields = "CategoryProductId,ProductId")]
        [Editable(true)]
        public int CategoryId { get; set; }

        [DisplayName("ProductId")]
        [Required(ErrorMessage = "Please select a Product")]
        [Remote("ValidateCategoryProduct", "ValidationLogic", AdditionalFields = "CategoryProductId,CategoryId")]
        [Editable(true)]
        public int ProductId { get; set; }

in my view I have the following under the category textbox
@Html.ValidationMessageFor(model => model.CategoryId, "*")
I also have the following under the productid textbox
@Html.ValidationMessageFor(model => model.ProductId, "*")

now we are good to go, the only issue left is that we need to figure out a way to apply validation result to both properties at once..... puzzled at the moment.

No comments: