Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event if there are validation errors?

I need to add an handle to any circumstance where a form validation fails.

I've read this, that explains that I have to add a handler as follows:

$('form').bind('invalid-form.validate', function () {
  console.log('form is invalid!');
});

But this event only fires when I try to submit the form.

I need to handle an event that's fired ANY time the form is post-validated (i.e. element loses focus etc.).

What I'm trying to achieve is, I have a large form (~50 fields), and it's splitted in Bootstrap tabs.
I want, that when there is any new validation failure or success, set or clear an error class in the tab title of the tab that contains the invalid/valid elements. P.S. my question is not on how to set those classes in the tabs. I only want to know what event(s) to handle in order to be notified upon each validation state change in the entire form.

like image 592
Shimmy Weitzhandler Avatar asked Apr 25 '15 23:04

Shimmy Weitzhandler


1 Answers

I need to add a handler to any circumstance where form validation fails.

$('input, textarea, select').on('focusout keyup', function() {
   if ($('form').valid()) {
       // do something
   }
});

I want, that when there is any validation error, set an error class in the tab title that contains the invalid elements.

Well, that's a bit different than what you originally asked about. (Ignore the first half of my answer.)

Use the highlight and unhighlight options along with jQuery DOM traversal to set and unset any class in the DOM you wish. highlight fires when something is invalid and unhighlight fires when it becomes valid. See this answer as an example.

Use the .setDefaults() method to set these options since you're using the unobtrusive-validation plugin and have no direct access to the .validate() method.

like image 153
Sparky Avatar answered Sep 28 '22 09:09

Sparky