Jason Y
Jason Y

Reputation: 11

Validating multiple form with same function in jquery

I have a page which contains a link that will open a window (via Bootstrap) that contains an add credit card form. This page also has a listing of credit cards with an edit link. When this is clicked, it will open a window (via Bootstrap) with an edit credit card form.

For both forms, there is a div tag named "errorMsgs" above the form fields where the error messages go. I want to validate the forms with the same jquery function.

What is happening is that the validation works for add credit card and the error message shows in the "errorMsgs" div section. However for the edit credit card form, the validation seems to work but no message appears. I suspect that the message is being added to the "errorMsgs" div section of the add form rather than the edit one because they are on the same page.

I was wondering how do I make it add to the "errorMsgs" tag of the credit card you are currently editing? As a customer could have more than one credit card on file, there could be multiple edit credit card forms. I thought I could still use the same ID, but pass the current form as a "parameter" so it could identify the correct div tag to add the message to, but I'm not too sure how to do that.

Below is a simplified version of my code:

jQuery function:

function validateCC(selector) {
    var form = $(selector);
    form.validate({
        invalidHandler: function(event, validator) {
        var errors = validator.numberOfInvalids();

            if (errors) {
                var message = ' ';
                message += '<p>Please correct the following errors:<br />';
                message += '<ul>\n';
                if (validator.errorList.length > 0) {
                    for (x=0;x<validator.errorList.length;x++) {
                        message += '<li>' + validator.errorList[x].message + '</li>\n';
                    }
                }
                message += '</ul>\n';
                message += '&nbsp;</p>\n';

                $("#errorMsgs").show();
                $("#errorMsgs").addClass("alert-error");
                $("#errorMsgs").html(message);


            } else {
                $("#errorMsgs").hide();
            }
        },
        rules: {
            customercc_ccnum: {
                minlength: 12,
                required: true
            }
        },
        messages: {
            customercc_ccnum: {
                required: "Number is required.",
                minlength: "Number should have at least 12 characters."
            }
        }
    });
}

$('.ccForm').click (function(){
    validateCC('.ccForm');
});

Add credit card form:

<form name="ccForm" class="ccForm" action="#myself#mcustomercc.add" method="post" id="submitCC">

<div class="row">
    <div class="span7">
        <div id="errorMsgs"></div>
    </div>
</div>

<div class="row">
    <div class="control-group">
    <div class="span2"><b>Credit Card Number:</b> <b class="mandatory">*</b></div>
    <div class="span5"> 
        <input type="text" name="customercc_ccnum" 
            size="17" 
            value=""
            placeholder="Credit Card Number"
            id="customercc_ccnum"
        >
    </div>

    </div>
</div>

<div class="row">
    <div class="span7">
        <input type="submit" name="addCC" value="Add" />
    </div>
</div>
</form> 

Edit credit card form:

<form  name="ccForm" class="ccForm" action="#myself#mcustomercc.update" method="post" id="editCC">
<div class="row">
    <div class="span7">
        <div id="errorMsgs"></div>
    </div>
</div>

<div class="row">
    <div class="control-group">
    <div class="span2"><b>Credit Card Number:</b> <b class="mandatory">*</b></div>
    <div class="span5"> 
        <div class="controls">
        <input type="text" name="customercc_ccnum" 
            size="17" 
            value="4111111111111111"
            placeholder="Credit Card Number"
            id="customercc_ccnum"
        >
        </div>
    </div>
    </div>
</div>

<div class="row">
    <div class="control-group">
    <div class="span7">
        <div class="controls">
        <input type="hidden" name="customercc_id" value="87">
        <input type="submit" name="editCC" value="Edit" />
        </div>
    </div>
    </div>
</div>
</form>

Any help would be appreciated!

Jason

Upvotes: 1

Views: 1302

Answers (1)

Sparky
Sparky

Reputation: 98718

Your code...

function validateCC(selector) {
    var form = $(selector);
    form.validate({
        // your options
    });
}

$('.ccForm').click (function(){
    validateCC('.ccForm');
});

Part of the problem is a misunderstanding about the .validate() method. It's only meant for initializing the plugin on your form... it is not supposed to be called on every click event. Since the click event is automatically captured by the plugin, you only need to call .validate() within a DOM ready event handler to initialize the plugin with your options.

However, the main problem is when you use a selector that contains multiple elements like a class, the methods from this plugin are only attached to the first matched element. (This is why you're seeing it only work on one form).

A jQuery .each() is used to solve this issue.

$(document).ready(function() {      // DOM ready event

    $('.ccForm').each(function() {  // select each form
        $(this).validate({          // initialize plugin on each form
            // your options
        });
    });

});

Upvotes: 1

Related Questions