VansFannel
VansFannel

Reputation: 45921

Validation doesn't work on dynamically added fields

I'm developing an ASP.NET MVC 5 app with Razor, C# and .NET Framework 4.6.1.

I have a problem with validation on an input fields that I generate dynamically with jQuery.

This is what ASP.NET Razor generates:

<input class="productClass" data-val="true" data-val-length="No más de 50 caracteres" data-val-length-max="50" data-val-required="Campo necesario" id="Configurations[0].Name" name="Configurations[0].Name" type="text" value="Estuche" />
<span class="field-validation-valid" data-valmsg-for="Configurations[0].Name" data-valmsg-replace="true"></span>

This is what I generate with jQuery:

<input type="text" name="Configurations[3].Name" id="Configurations[3].Name" data-val-required="Campo necesario" data-val-length-max="50" data-val-length="No más de 50 caracteres" data-val="true" class="productClass" ></input>
<span data-valmsg-replace="true" data-valmsg-for="Configurations[3].Name" class="field-validation-valid"></span>

Both have the same data fields with the same value. The only different is the one I generate has different order in its attributes.

The validation works on inputs auto generated by ASP.NET Razor, but mine doesn't work. I can set an empty value on NAME and it doesn't validate it.

Do you see anything wrong? Any advice?

Upvotes: 4

Views: 1302

Answers (1)

visvesan
visvesan

Reputation: 86

Add the following code while generate the dynamic fields in script:

$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

Upvotes: 7

Related Questions