Brad
Brad

Reputation: 12272

jquery validate errors in modal, triggering modal more than once

I am displaying the (http://jqueryvalidation.org/) errors in a modal.

When the user does not fill in the email and code fields, it displays a modal with an error message saying they need to fill out those two fields, I click close, then it displays another modal, but it only displays one error. Two things that are going wrong, it should not display the modal after I click close in the modal, 2nd thing: it is only displaying the last error message when the second modal shows up (after clicking the close button in the first modal).

Screenshots provided to show you what I am talking about

enter image description here enter image description here enter image description here

I did a count++ and printed that out in the console and it is triggering showErrors method more than once. Am I using the wrong method? I used showErrors because I could append the errors to the message variable and then display them in the modal.

$("#enter-code-form").validate({
    //ignore: [],
    rules: {
        email: {
            required: true,
            email: true,
        },
        code: {
            required: true,
            minlength: 8,
            maxlength: 8,
        },
    },

    messages: {
        code: {
            required: "Please provide a valid code",
            minlength: "You need to provide a eight alpha-numeric code",
            maxlength: "You need to provide a eight alpha-numeric code",
        },
        email: {
            required: "Please provide email",
            email: "Your email address must be in the format of [email protected]"
        }
    },

    showErrors: function(errorMap, errorList) {
        var message = '';
        var element = '';

        $.each(errorList, function (index, error) {
            message += '<p>' + error.message + '</p>';       
            element += error.element;        
        });

        display_modal('You have an error', message);
        console.log(message);
        // console.log(element);
    }
});

function display_modal(title, message)
{
    $("#error-modal").modal("show");
    $('.modal-title').show().html(title);
    $('.modal-body-message').show().html(message);
}

Upvotes: 1

Views: 1154

Answers (1)

Brad
Brad

Reputation: 12272

I had to use the invalid handler instead:

invalidHandler: function(form, validator) {
    var errors = validator.numberOfInvalids();

    if (errors) {
        var errors = "";

        if (validator.errorList.length > 0) {
            for (x=0;x<validator.errorList.length;x++) {
                errors += "<p>" + validator.errorList[x].message + "</p>";
            }
        }
        display_modal('You have an error', errors);
    }
    validator.focusInvalid();
},

Upvotes: 2

Related Questions