Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display jQuery Validation error container only on submit

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 errors, I have an issue. The problem is that it shows the container with all errors when I am in all fields, but I would like to display the error container only when the user presses the submit button (but still show inline errors beside the control when losing focus).

The problem is the message in the container. When I took off the code as mentioned in the answer below for the container, the container output just displays the number of errors in plain text.

What is the trick to get a list of detailed error messages? What I would like is to display "ERROR" next to the control in error when the user presses the tab button, and to have a summary of everything at the end when he presses submit. Is that possible?

Code with all input from here:

    $().ready(function() {
        var container = $('div.containererreurtotal');

        // validate signup form on keyup and submit
        $("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
          var err = validator.numberOfInvalids();
          if (err) {
            container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
            container.show();
          } else {
            container.hide();
          }
        }).validate({
                    rules: {
                            nickname_in: {
                                    required: true,
                                    minLength: 4
                            },
                            prenom_in: {
                                    required: true,
                                    minLength: 4
                            },
                            nom_in: {
                                    required: true,
                                    minLength: 4
                            },
                            password_in: {
                                    required: true,
                                    minLength: 4
                            },
                            courriel_in: {
                                    required: true,
                                    email: true
                            },
                            userdigit: {
                                    required: true
                            }
                    },
                    messages: {
                            nickname_in: "ERROR",
                            prenom_in: "ERROR",
                            nom_in: "ERROR",
                            password_in: "ERROR",
                            courriel_in: "ERROR",
                            userdigit: "ERROR"
                    }

                    ,errorPlacement: function(error, element){
                            container.append(error.clone());
                            error.insertAfter(element);
                    }

            });
    });
like image 341
Patrick Desjardins Avatar asked Nov 12 '08 21:11

Patrick Desjardins


People also ask

How can I disable enable submit button after jQuery validation?

You can only disable it after the form has successfully passed validation. Use the plugin's submitHandler option for this as it's fired on a button click only when the form has passed validation. $(). ready(function() {... is not recommended as per jQuery documentation.

How remove validation after field is valid using jQuery?

validate( ... ... ); $(". cancel"). click(function() { validator. resetForm(); });

What is validator addMethod in jQuery?

addMethod( name, method [, message ] ) Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.

What is valid () in jQuery?

valid()Returns: Boolean Description: Checks whether the selected form is valid or whether all selected elements are valid.


2 Answers

First your container should be using an ID instead of a class.. (I'm going to assume that ID is 'containererreurtotal')

Then Try this..

    $().ready(function() {

        $('div#containererreurtotal').hide();

        // validate signup form on keyup and submit
        $("#frmEnregistrer").validate({
            errorLabelContainer: "#containererreurtotal",
            wrapper: "p",
            errorClass: "error",
            rules: {
                nickname_in: { required: true, minLength: 4 },
                prenom_in: { required: true, minLength: 4 },
                nom_in: { required: true, minLength: 4 },
                password_in: { required: true, minLength: 4 },
                courriel_in: { required: true,  email: true },
                userdigit: { required: true }
            },
            messages: { 
                nickname_in: { required: "Nickname required!", minLength: "Nickname too short!" },
                prenom_in: { required: "Prenom required!", minLength: "Prenom too short!" },
                nom_in: { required: "Nom required!", minLength: "Nom too short!" },
                password_in: { required: "Password required!", minLength: "Password too short!" },
                courriel_in: { required: "Courriel required!", email: "Courriel must be an Email" },
                userdigit: { required: "UserDigit required!" }
            },
            invalidHandler: function(form, validator) {
                $("#containererreurtotal").show();
            },
            unhighlight: function(element, errorClass) {
                if (this.numberOfInvalids() == 0) {
                    $("#containererreurtotal").hide();
                }
                $(element).removeClass(errorClass);
            }    

        });
    });

I am assuming here that you want a <p> tag around each of the individual errors. Typically I use a <ul> container for the actual container (instead of the div you used called 'containererreurtotal') and a <li> for each error (this element is specified in the "wrapper" line)

If you specify #containererreurtotal as display: none; in your CSS, then you dont need the first line in the ready function ( $('div#containererreurtotal').hide(); )

like image 123
FerrousOxide Avatar answered Oct 21 '22 18:10

FerrousOxide


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 <label> 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

like image 43
Serxipc Avatar answered Oct 21 '22 18:10

Serxipc