JQuery Validate Custom Error messages in multiple places (top of form and at form level)

后端 未结 1 630
南旧
南旧 2020-12-10 19:29

I am using the JQuery Validate plugin to handle validation for my forms. I have a requirement to have the error at 2 places:

  1. Top of the form
  2. At the fi
相关标签:
1条回答
  • 2020-12-10 19:58

    Quote OP:

    "so how would i build the code to have it at both locations?"

    See the showErrors option as contained in the documentation.

    This will give you a good start (needs some tweaking)...

    $("#myform").validate({
        // your rules here,
    
        // call back for placement of messages within form
        errorPlacement: function (error, element) {
            error.insertBefore(element);
        },
    
        // callback for custom error display
        showErrors: function (errorMap, errorList) {
    
            // summary of number of errors on form
            var msg = "Your form contains " + this.numberOfInvalids() + " errors, see details below.<br/>"
    
            // loop through the errorMap to display the name of the field and the error
            $.each(errorMap, function(key, value) {
                msg += key + ": " + value + "<br/>";
            });
    
            // place error text inside box
            $("#errormessages").html(msg);
    
            // also show default labels from errorPlacement callback
            this.defaultShowErrors(); 
    
            // toggle the error summary box
            if (this.numberOfInvalids() > 0) {
                $("#errormessages").show();
            } else {
                $("#errormessages").hide();
            }
    
        } // end showErrors callback
    });
    

    Working DEMO: http://jsfiddle.net/M5pzA/

    0 讨论(0)
提交回复
热议问题