<span asp-validation-for can not trigger if html is appended.

mc 5,426 Reputation points
2022-06-21T10:05:44.497+00:00

If I use jquery.html("");

append html

<input type="text" asp-for="MyValue" />  
<span asp-validation-for="MyValue" ></span>  

it can not validate for it.

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Othusitse Seth Dylan Phefo 1 Reputation point
    2022-06-21T18:38:12.243+00:00

    Jquery validation doesn't work when you dynamically add to the DOM because it adds attributes used in validation on form load. The workaround is to call it again after appending html and this is referred to as unobtrusive validation. Once the validators have been applied for a document, any other validators of the dynamic content(partial views or jquery induced html controls) will not be applied. Once we reload the validators, it will bind rules defined inside the model with rules implementation provided by JQuery library, so validation will be performed seamlessly.

    For instance, lets say you have the following code where an html element is appended when you click a button:

    $('#add').on('click', function () {  
                              //append html  
                               $("#form").append("<span asp-validation-for='MyValue' ></span>");   
      
                               // delete and reload validator (assuming that form.validate() has been called on form load)   
                               $("#form").removeData("validator");  
                               $("#form").removeData("unobtrusiveValidation");  
      
                               //Enable unobtrusive validation to attach attributes to appended html element  
                               //to bind  rules defined  with rules implementation provided by JQuery library.  
                               $.validator.unobtrusive.parse("form");  
        });  
    

    The other option (instead of reloading validators) you have is to inject the new rules as shown here.

    Access the form's unobtrusiveValidation data using the jquery data method ($(form).data('unobtrusiveValidation')) and access the rules collection and add the new elements attributes.

    Reference
    https://mfranc.com/javascript/unobtrusive-validation-in-partial-views/
    https://itecnote.com/tecnote/asp-net-mvc-unobtrusive-validation-not-working-on-dynamically-added-partial-view/

    Please vote for my answer if it works for you

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.