duddosai duddosai - 1 year ago 76
jQuery Question

jquery validation: Show error message for one control alone

I'm using jquery validate plugin for validating my form. Version: jQuery Validation Plugin v1.15.0. This is how I've tried:

errorplacement: function(error, element) { },
customername: "required",
required: true,
email: true
equalTo: '#password'
equalTo: 'The two passwords do not match!'

By using this, I've mentioned that all my controls are required. But, I want to show the error message for confirmpassword alone. But, default error message "This Field is required", is displayed for all other controls.

My requirement is, how can I show the error message for confirmpassword control alone, provided all the other fields are required. How can I do that?

Answer Source
  1. In the messages object, assign the error message to the field name instead of the rule name. This way the same message will be displayed for all errors on this field.

    messages: {
        confirmpassword: 'The two passwords do not match!'
  2. It's spelled errorPlacement, not errorplacement.

  3. You should not leave errorPlacement empty. Instead put a return false inside and this function is disabled. However, you do not need errorPlacement in order to disable the default messages. See #4 below.

  4. Use showErrors instead of errorPlacement. With showErrors, you can control each message individually and this function will automatically suppress the default error messages. The errorMap argument contains all field names and error messages as key/value pairs. Pick out the confirmpassword message with errorMap.confirmpassword.

    showErrors: function(errorMap, errorList) {
        var message = (errorMap.confirmpassword) ? errorMap.confirmpassword : '';

DEMO: jsfiddle.net/Ljs96zcq/