markA
markA

Reputation: 1609

jQuery Validator Custom Methods: How to use with multiple forms on same page?

I have a form requesting user input for start and end lengths and it can be repeated a variable number of times on a page depending on how many sections the user wants to put in. I am trying to add some validation. I added a custom validator method inside a function that I call onChange of either field to check that the end length is greater than the start and it is working.

When the user calls a second form on to the page, the method breaks and stops working; it appears to hold whatever error message it has at the time and no matter what I change it persists, unless I go outside of the range bounds which still validate properly.

The input tag has this on both fields: onchange="validateTheForm(this.form);"

Here is the code in my .js file, I call this on the form every time either input changes:

var validateTheForm = function(theForm) {
    $.validator.addMethod("endGreaterThanBegin", function(value, element) {
        return parseInt($('#endPoint').val(), 10) > parseInt($('#startPoint').val(), 10);
    }, "End Point Should be Greater than Start");

    $(theForm).validate({
        rules: {
            startPoint: {
                required: true,
                range: [0, 100]
            },
            endPoint: {
                required: true,
                range: [1, 100],
                endGreaterThanBegin: true
            }
        }
    });
    return true;
}

I thought it might be an issue with trying to add the method over and over, but that happens every time I change either field on the first form and never breaks. I'm wondering if it has to do with setting the variable tied to the first form when the method is created and never updating them to the new forms.

Upvotes: 0

Views: 400

Answers (1)

Jayendra
Jayendra

Reputation: 52769

Define the rules and apply the validator once and use the valid method to validate the form.

Demo - http://jsfiddle.net/2hA8M/17/

function validateTheForm(){
    $('#signupform').valid();
}

Upvotes: 1

Related Questions