Client side validation for dynamic generated forms in dotnet core mvc

Author : Sachin Sharma
Published On : 05 Apr 2023

Most of the documentation for validation in dotnet core MVC talks about view models with data annotations and that obviously works really well and easily. Here we will discuss about client side validation for dynamic forms in dotnet core mvc.

 

$("#formId").data("validator", null);
 $.validator.unobtrusive.parse($("#formId"));

 

use this code to activate client side validation on dynamic form hopefully before this you know about how to apply client side validation in mvc.

dynamic

Click on MakeBy + icon AddMakeBy popup open this modal popup bind dynamically.

<form id="frmMakeBy" method="post">                       
                        <div class="row">
                            <div class="col-12">
                                <div class="form-group">
                                    <input type="text" class="form-control" asp-for="Name" autocomplete="off" placeholder="Make By name" />
                                    <span class="text-danger" asp-validation-for="Name"></span>
                                </div>
                            </div>
                           
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="form-group">
                                    <button type="button" class="btn btn-primary" onclick="makeBy.add()">Add</button>                                    
                                </div>
                            </div>
                        </div>
                    </form>


<script>

  var makeBy = {

 add: function () {
            $("#frmMakeBy").data("validator", null);
            $.validator.unobtrusive.parse($("#frmMakeBy"));

            if ($('#frmMakeBy').valid()) {
                jData.post('/configurator/makeBy/addMakeBy', $('#frmMakeBy').serialize(), function (res) {
                    if (res.status === 1) {
                          alert('data added successfully.');
                    }
                    alert('error');
                });
            }
        },

 post: function (url, requestData, successFunc) {
        $.ajax({
            url: url,            
            data: requestData,
            type: "POST",
            success: function (res) {
                successFunc(res);
            }
        });
    },

}

};

</script>

 

With the help of above code can initialize client side validation of dynamic forms in mvc.

Comments

No comments have been added to this article.

Add Comment