I'm trying to validate a form using the jQuery validation plugin. I have rules targeting both single and multiple properties. I would like to customize the plugin behaviour in the two cases. In particular I would like to show the errors related to a single field close to that field and the errors caused by multiple fields in a validation summary.
The configuration of the validator object is something like:
var options = { errorClass: "input-validation-error", errorElement: "span", errorPlacement: function(error, element) { var fieldName = element.attr("name"); var messageSpan = fieldToMessageMappings[fieldName];
$(messageSpan).empty(); $(messageSpan).removeClass("field-validation-valid"); $(messageSpan).addClass("field-validation-error"); error.removeClass("input-validation-error"); error.attr("_for_validation_message", messageSpan); error.appendTo(messageSpan); }, showErrors: function(errorMap, errorList) { /* errorMap contains something like: errorMap: { Username: "The username field is required", Password: "The Password and Confirm password fields must match", ConfirmPassword: "The Password and Confirm password fields must match" } */
// how can I know here which is the rule violated? // Password: required or Password: passwordMatch? this.defaultShowErrors(); }, invalidHandler: function(form, validator) { }, onkeyup: false, onfocusout: false, messages: { Username: { required: "The Username field is required" } Password: { required: "The Password field is required", passwordMatch: "The Password and Confirm password fields must match" } ConfirmPassword: { required: "The Confirm password field is required" passwordMatch: "The Password and Confirm password fields must match" } Email: { regex: "The Email field is invalid" } }, rules: { Username: { required: true } Password: { required: true, property1: "Password", property2: "ConfirmPassword" } /* the two field names to compare */ } ConfirmPassword: { required: true, passwordMatch: { property1: "Password", property2: "ConfirmPassword" } /* the two field names to compare */ } Email: { regex: "^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" } }, success: function(label) { var messageSpan = $(label.attr("_for_validation_message")); $(messageSpan).empty(); $(messageSpan).addClass("field-validation-valid"); $(messageSpan).removeClass("field-validation-error"); } }
form.validate(options);
The validation code for passwordMatch is something similar to:
<script language="javascript" type="text/javascript"> jQuery.validator.addMethod("passwordMatch", function(value, element, param) { var property1 = param["property1"]; var property2 = param["property2"]; var value1 = $("#" + property1).val(); var value2 = $("#" + property2).val(); if (value1 != value2) { return false; } return false; }, ""); </script>
Is there a way to accomplish this? Thanks in advance. Nicola