How to use JQuery Validate to create a popup with all form error when the submit button is clicked?

Posted by Larry on Stack Overflow See other posts from Stack Overflow or by Larry
Published on 2010-06-17T16:25:41Z Indexed on 2010/06/17 19:43 UTC
Read the original article Hit count: 219

I am using the JQuery Validation plugin for client side form validation. In addition to the colorful styling on invalid form fields, my client requires that a popup message be shown. I only want to show this message when the submit button is click because it would drive the user crazy otherwise. I tried the following code, but errorList is always empty. Anyone know the correct way to do something similar.

function popupFormErrors(formId) {
  var validator = $(formId).validate();
  var message = '';
  for (var i = 0; i < validator.errorList.length - 1; i++) {
    message += validator.errorList[i].message + '\n';
  }

  if (message.length > 0) {
    alert(message);
  }
}

$('#btn-form-submit').click(function(){
  $('#form-register').submit(); 
  popupFormErrors('#btn-form-submit');
  return false;
});

$('#form-register').validate({
  errorPlacement: function(error, element) {/* no room on page */},
  highlight: function(element) { $(element).addClass('invalid-input'); },
  unhighlight: function(element) { $(element).removeClass('invalid-input'); },
  ...
});

Update From the info in the accepted answer I came up with this.

var submitClicked = false;

$('#btn-form-submit').click(function() {
  submitClicked = true;
  $('#form-register').submit();    
  return false;
});

$('#form-register').validate({
  errorPlacement: function(error, element) {/* no room on page */},
  highlight: function(element) { $(element).addClass('invalid-input'); },
  unhighlight: function(element) { $(element).removeClass('invalid-input'); },
  showErrors: function(errorsObj) {
    this.defaultShowErrors();
    if (submitClicked) {
      submitClicked = false;
      ... create popup from errorsObj...
    }
  }
  ...
});

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery