duddosai duddosai - 2 months ago 13
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:

$("#myform").validate(
{
errorplacement: function(error, element) { },
rules:
{
customername: "required",
mobileno:"required",
emailid:{
required: true,
email: true
},
phoneno:"required",
projectsponsor:"required",
status:"required",
loginid:"required",
password:"required",
confirmpassword:{
required:true,
equalTo: '#password'
}
},
messages:
{
confirmpassword:{
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
  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 : '';
        $("#message").html(message);
    },
    

DEMO: jsfiddle.net/Ljs96zcq/

Comments