views:

818

answers:

4

I'm trying to use the JQuery validator on a form and am trying to figure out to get the messages of the errors in the invalidHandler option (or if there's somewhere else, do tell).

When a user clicks the submit button, whatever the first error is, I want to display an alert box with the message of the error. I don't want the error to be written on the document. I can't seem to figure out how to get the error messages to use in an alert after validation. I only found how to get the elements, and that doesn't really help me.

Pulling out from the example, here's some code I'm testing with

$(document).ready(function() {
    $('#commentForm').validate({
     invalidHandler: function(f, v) {
      var errors = v.numberOfInvalids();
      if (errors) {
       var invalidElements = v.invalidElements();
       alert(invalidElements[0]);
      }
     }
    });
});

and

 <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
+1  A: 

You should not use alert,

But if you really want to use that. Solution depend of how plugin add dom elements but you can remove those dom elements in invalidHandler. So let those dom element added but remove it.

Other option is, you should patch plugin you use for validation and instead of adding dom show alert.

nexneo
I've already done what I could trying to convince the client that alert error messages from validation isn't the best solution, but he insisted. Ah well.
Johnny O.
A: 

Overloading showErrors worked as expected. I just needed to get the first error message.

 showErrors: function(errorMap, errorList) {
  alert(errorList[0].message);
 }

Also remember to take a look at the onfocusout and onkeyup options, else you'll get continuous messages.

Johnny O.
+2  A: 

MUST check errorList.length

if (errorList.length > 0) alert(errorList[0].message);
AprilBriz
+1  A: 

This works for me...

    invalidHandler: function(form, validator) {
      var errors = validator.numberOfInvalids();
      if (errors) {
        var message = errors == 1
          ? 'Please correct the following error:\n'
          : 'Please correct the following ' + errors + ' errors.\n';
        var errors = "";
        if (validator.errorList.length > 0) {
            for (x=0;x<validator.errorList.length;x++) {
                errors += "\n\u25CF " + validator.errorList[x].message;
            }
        }
        alert(message + errors);
      }
      validator.focusInvalid();
    }
Charles Forsyth