Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include the field label in a jquery Validate error message

I am displaying my jquery validate errors at the top of the page. I want to include the text value of the label associated with each invalid field next to each message. How is this done. Here is my jquery.

$(document).ready(function(){
    $("#reqAccount").validate({
            errorClass: "error-text",
            validClass: "valid",
            errorLabelContainer: "#errorList",
            wrapper: "li ",
            highlight: function(element, errorClass, validClass) {
                $(element).addClass("error-input").addClass(errorClass).removeClass(validClass);
             },
             unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass("error-input").removeClass(errorClass).addClass(validClass);
             }
        });
    });
like image 747
coder Avatar asked Feb 19 '11 23:02

coder


1 Answers

Here's how I ultimately updated the messages to include the text value of the label. The ids of the text field were found in the errorMap, so I used them to find the label with a similar ID and appended them to the errorList. Please comment if there's a better way to do this.

  $(document).ready(function(){
    $("#reqAccount").validate({
        errorClass: "error-text",
        validClass: "valid",
        errorLabelContainer: "#errorList",
        wrapper: "li class='indent error-text'",
        showErrors: function(errorMap, errorList) {
            var i = 0;
            var labelText = new Array(this.numberOfInvalids());
            $.each(errorMap, function(name, value) {
                labelText[i] = $("#" + name + "Label").text();
                i++;
            });
            i = 0;
            $.each(errorList, function(name, value) {
                this.message = labelText[i] + " " + this.message;
                i++;
        });
            this.defaultShowErrors();

         },

        highlight: function(element, errorClass, validClass) {
            $(element).addClass("error-input").addClass(errorClass).removeClass(validClass);
         },
         unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass("error-input").removeClass(errorClass).addClass(validClass);
         }
    });
});
like image 132
coder Avatar answered Sep 30 '22 12:09

coder