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

半世苍凉 提交于 2020-01-13 11:09:15

问题


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);
             }
        });
    });

回答1:


If I understand you correctly, I think you might be able to use showErrors:

$(".selector").validate({
   showErrors: function(errorMap, errorList) {
      //use the fn params to get a map of current errors,
      //then append to your <li> elements
   }
});

Ref. http://docs.jquery.com/Plugins/Validation/validate under 'options' tab.




回答2:


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);
         }
    });
});



回答3:


Coder thanks for the answer that you posted, the showErrors code you posted helped me out a lot. However, I wasn't able to get it to work for me with the onfocusout set to true. I had to modify your code a little bit, and hopefully this will help anyone else out there who is dealing with this same problem.

showErrors: function(errorMap, errorList) {
                var i = 0;
                var labelText = new Array(this.numberOfInvalids());

                $.each(errorMap, function(name, value) {
                    //I had to change the following line to get the for attribute of the 
                    //label that matches the id of the name
                    var label = $("label[for='" + $('#' + name).attr('id') + "']").text();
                    labelText[i] = label;
                    i++;
                 });
                i = 0;
                $.each(errorList, function(name, value) {
                    //This is where I ran into issues.  With the code you had earlier, the labelText kept
                    //getting appended every time I would change focus from an input.  To get rid of that
                    //I had to run a couple of checks
                    var semi = labelText[i].indexOf(':');
                    var requiredString = 'This field is required';
                    var check = labelText[i].indexOf(requiredString); 

                    if (check != -1) {
                        if (semi != -1 && labelText[i].indexOf(':', semi + 1) != -1) {
                            var indexOfSemi = labelText[i].indexOf(':'); 
                            labelText[i] = labelText[i].substr(0, indexOfSemi); console.log(labelText[i]);
                            this.message = hold + ": " + this.message;
                        }
                    } else {
                        this.message = labelText[i] + " " + this.message;d
                        i++;
                    }
                });
                this.defaultShowErrors();
            },

Just wanted to say thanks, and hopefully this'll help someone else out as well.




回答4:


$.validator.messages.required = function (param, input) {
     return 'The ' + $("label[for='"+ input.name +"'].lblRequired").text()
     + ' field is required';
}

I use this and it works perfectly for me. When you select the corresponding label with jQuery, be sure to add an additional identifier to your label (in my case I added the class ".lblRequired"). When the validator fires, it creates new labels with the same "for" which associates them to the inputs. So if you don't add a class or another way to identify your original labels, you'll end up with a mess as you select the wrong label for subsequent validations and the labels will continue to compound with error messages.



来源:https://stackoverflow.com/questions/5054120/how-do-i-include-the-field-label-in-a-jquery-validate-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!