Skip to content Skip to sidebar Skip to footer

Jquery Form Validation - Success + Showerrors

I'm using the jQuery Validation Plugin and want to run my own code when the plugin detects a valid or invalid input. I've figured out that the two .validate() options I need are su

Solution 1:

"showErrors" is not called just when an error is detected, it's called everytime you change the input, regardless the value you typed.

"showErrors" receives two parameters: "errorMap" and "errorList". To verify if there really was an error you have to check one of those values:

showErrors: function(errorMap, errorList) {
  if (errorsList.length > 0) {
    console.log('error');
  }
}

You can also handle the "success" event inside the showErrors function, since it's called in the current validator context.

showErrors: function(errorMap, errorList) {
  if (errorsList.length == 0) {
    this.currentElements.addClass("success");
  }
}

Solution 2:

Figured it out... sort of.

I replaced showErrors with highlight, which allows me to run a callback on either valid or invalid entries.

However, the plugin still displays the default error messages -- probably since I'm not doing anything with showErrors. So I had to hack that by setting an empty string for the message on each field:

var validator = $('#form').validate({
  rules: {
    name: "required",
    email: {
      required: true,
      email: true
    }
  },
  messages: {
    name: '',
    email: ''
  },
  success: function() {
    console.log('success');
  },
  highlight: function() {
    console.log('highlight');
  }
}

Certainly not as clean as I would like, so if anyone has a better way that would be great.

Post a Comment for "Jquery Form Validation - Success + Showerrors"