views:

206

answers:

1

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...
    }
  }
  ...
});
+1  A: 

You should really look at using the following option for jQuery Validation

showErrors

here is a link to the documentation http://docs.jquery.com/Plugins/Validation/validate#options

John Hartsock
Thanks for the help. Is there a way to keep the original showErrors function (it add/removes the 'invalid-input' class from form elements) and still include some of my own code?
Lawrence Barsanti
to use the original show Errors functionality use this.defaultShowErrors
John Hartsock