Julian Dormon
Julian Dormon

Reputation: 1779

MVC 4 adding a custom unobtrusive validator

I have a form with elements that may be contained within collapsed accordion divs. When someone submits the form and the unobtrusive validator catches an error on one or more of these "hidden" form elements, I want the collapsed accordion to open so they can see their errors.

After doing a little research, I found a suggestion here, Using unobtrusive validation in ASP.NET MVC 3, how can I take action when a form is invalid? which says to make my own unobtrusive adapter. So I did, it is here:

$.validator.unobtrusive.adapters.add(
'collapsevalidation',
  function () {
   var tabs = $('.collapse').not('.in');
   //console.log("tabs.length: " + tabs.length);
   $(tabs).each(function () {
       if ($(this).has('.field-validation-error').length) {
           id = "#" + $(this).attr('id');
           //console.log("id: " + id);
           $("[data-target='" + id + "']").collapse('show');
       }
   });

}(jQuery));

The adapter plugin has been added to my page and now I am trying to figure out how to "hook" it in but I cannot seem to do so. So far I have added the following to my page:

jQuery.validator.unobtrusive.adapters.add("collapsevalidation");

This however does not seem to be working. When I produce an error on submit, the console.log lines to not write.

I understand that this is a custom adapter because it does not apply to a specific element and does not return anything, like a bool.

Can someone help complete this, please. Thanks!

Upvotes: 1

Views: 311

Answers (1)

Julian Dormon
Julian Dormon

Reputation: 1779

While I did not find an answer directly to the above, I did get my desired result using the following:

$("form").bind("invalid-form.validate", function () {
   //My code here
}

Upvotes: 1

Related Questions