Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate dynamically added control

How can I add the dynamically added control to validation?

<div class="editor-field">
    @*@Html.EditorFor(model => model.Middlename)*@
    <div id="x"></div>

    <script type="text/javascript">

        $(function () {

            var newTextBoxDiv = $(document.createElement());

            newTextBoxDiv.html('<input type="text" name="Middlename" id="Middlename" width="100" data-val="true" data-val-required="The Middleneim field is required." />');

            newTextBoxDiv.appendTo('#x');
        });

    </script>

    @Html.ValidationMessageFor(model => model.Middlename)
</div>

I noticed that when I don't use the ready function, i.e.

<script type="text/javascript">


var newTextBoxDiv = $(document.createElement());

newTextBoxDiv.html('<input type="text" name="Middlename" id="Middlename" width="100" data-val="true" data-val-required="The Middleneim field is required." />');

newTextBoxDiv.appendTo('#x');
</script>

,the client-side validations kicks-in. Is there a way to explicitly include the deferredly-created inputs to validations?

like image 973
Green Lantern Avatar asked Mar 29 '11 06:03

Green Lantern


1 Answers

UPDATE: This answer is if you use jquery unobtrusive validation, you did not wrote what you use.

First, add this plugin to jQuery ready: http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/

Mind that you must add your element inside of form tag. Lets say that you have some wrapper around your tag, I will call it "element".

After you append your element to DOM, call this:

$.validator.unobtrusive.parseDynamicContent($(element).find("form").selector);
var form = $(element).find("form");
$(form).valid();
    $(form).find("input").each(function () {
        $(this).blur(function () {
            $(this).valid();
        });
    });
    $(form).find("select").each(function () {
        $(this).change(function () {
            $(this).valid();
        });
like image 93
Goran Obradovic Avatar answered Oct 08 '22 18:10

Goran Obradovic