MVC 4 Validation Attribute is not working for dynamically added fields

1k views Asked by At

Here are my Product and ProductItem classes/models:

    public class Product
        {
            public int ProductId { get; set; }
            [Required(ErrorMessage="Enter Name")]
            public string Name { get; set; }
            public List<ProductItem> productitems { get; set; }
            [Required(ErrorMessage="Enter Price")]
            public decimal Price { get; set; }
        }
    public class ProductItem
        {
            [Required(ErrorMessage="Select Raw Material")]
            public int RawMaterial { get; set; }
            [Required(ErrorMessage="Enter Quantity")]
            public decimal Qty { get; set; }
        }

For ProductItem I am adding its fields dynamically with jQuery, as you can see here:

$("#btnAddProductItem").click(function () {
        $.getJSON("/rawmaterial/GetRawMaterials", null, function (data) {
            var productItem = $("<tr class='productItem' id='productItem-0'><td><select id='rmlist-0' name='productitems[0].RawMaterial'></select><span class='field-validation-valid' data-valmsg-for='productitems[0].RawMaterial' data-valmsg-replace='true'></span></td><td><input type='text' id='rmqty-0' name='productitems[0].Qty'/><span class='field-validation-valid' data-valmsg-for='productitems[0].Qty' data-valmsg-replace='true'></span></td></tr>");
            $("#productItem").append(productItem);
            $("#rmlist-0").addItems(data);
        });
    });

Now the validation attributes applied on Name and Price are working fine but not on the fields added dynamically (i.e. "RawMaterial" and "Qty").

Please give me the suggestions how this validation will work ?

Note: For testing purpose I have just added the first object of the List indexed with 0.

1

There are 1 answers

1
brainless coder On

There are several ways to accomplish this -

  1. PARTIAL VIEW: Since you are using Server Side data annotation as I see from the class definitions, then it is not a good idea to load dynamically with js. Because you will miss out all the validation that MVC 4 could have created automatically. So, the best solution I would suggest is taking the code that you are adding dynamically to a partial view file and then get the html with ajax call and then populating the HTML.

  2. JS VALIDATION: But, if it is a must that you should use JS, then you have to add all the validation items yourself. To do that you have to do some extra works -

    • First, inspect the HTML with any developer tools, you will notice that there is a <span> attribute appended after each item to show the error which has a target mentioned. You have to append similar attributes to your elements

    • With MVC 4 unobtrusive validation, all the validation attributes and rules are added with the target element with data attributes. Each one is based one the validation they stands for. You have you create attributes similar to that.

    • Finally, after adding all the validation items in JS, reset the form so that it parses the new validations added and work accordingly. The code to parse the validations are here -

      var form = $("form") //use more specific selector if you like
      form.removeData("validator").removeData("unobtrusiveValidation");
      $.validator.unobtrusive.parse(form);
      

But I would prefer the partial view solution, since it will require least amount of re-work and also gives you option to keep all your validation in one place. You don't have to worry about new validations to be ported to js in future.