Friday, 19 February 2021

MVC - Custom Validation - Remote - Additional Fields - Validate on each field change

 

 Watch this example on YouTube


 

Javascript code

@section Scripts{
    
    <script type="text/javascript">
        $(document).ready(function () {
            validateRemote($("form"));
        });
        function validateRemote($form) {
            var remoteElements = $form.find("[data-val-remote]");
            $.each(remoteElements, function (i, element) {
                var $element = $(element);
                var additionalFields = $element.attr("data-val-remote-additionalfields");
                if (additionalFields.length == 0) return;

                var fieldNames = additionalFields.split(",");
                var fNames = $.map(fieldNames, function (fieldName) { return fieldName.replace("*.", ""); });
                $.each(fNames, function (i, fieldName) {
                    $form.find("[id$=" + fieldName + "]").change(function () {
                        if ($element.is(':enabled')) {
                            $element.removeData("previousValue");
                            $element.valid();
                        }
                    });
                });
            });
        }
    </script>    
}

 

No comments:

Post a Comment