How to display jQuery Validation error container only on submit

后端 未结 6 835
南笙
南笙 2021-02-07 10:14

I am trying to make the Validation plugin work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the err

6条回答
  •  长情又很酷
    2021-02-07 10:49

    You will find the documentation for the meta option in http://docs.jquery.com/Plugins/Validation/validate#toptions

    If you want to display the errors beside the inputs AND in a separate error container you will need to override the errorPlacement callback.

    From your example:

    ...
                        courriel_in: "ERROR",
                        userdigit: "ERROR"
                }
                ,errorContainer: container
    
                ,errorPlacement: function(error, element){
                    var errorClone = error.clone();
                    container.append(errorClone);
                    error.insertAfter(element)              
                }
    
                // We don't need this options
                //,errorLabelContainer: $("ol", container)
                //,wrapper: 'li'
                //,meta: "validate"
        });
     ...
    

    The error parameter is a jQuery object containing a tag. The element parameter is the input that has failed validation.

    Update to comments

    With the above code the error container will not clear errors because it contains a cloned copy. It's easy to solve this if jQuery gives a "hide" event, but it doesn't exist. Let's add a hide event!

    1. First we need the AOP plugin
    2. We add an advice for the hide method:

                  jQuery.aop.before({target: jQuery.fn, method: "hide"},
                      function(){
                          this.trigger("hide");
                      });
      
    3. We bind the hide event to hide the cloned error:

              ...
              ,errorPlacement: function(error, element){
                  var errorClone = error.clone();
                  container.append(errorClone);
                  error.insertAfter(element).bind("hide", function(){
                      errorClone.hide();
                  });
              }
              ...
      

    Give it a try

提交回复
热议问题