开发者

How to require different rules in jQuery Validate on a method that' used for multiple pages?

I have several contact forms, which all use the same method to to validate the form contents using jQuery Validate. Some 开发者_运维百科pages require fields that others do not. I need to use IF statements to detect which page it is, and if the page requires the field, then it should be added to the rules parameter in the call to the validate() method.

Can someone give me an example of how to do this so it will work? Here's what I need to do (which obviously doesn't work). I can't declare all of the contents of rules in a var above because of all the spaces:

$("#contactForm").validate( {
    rules: {
        name: {
            required: true
        },
        phone: {
            required: true
        },
        if ( page === "contactJoe" ) {
            subject: {
                required: true
                },
        }
        email: {
            required: true,
            email: true
        }
    }
});     


I'd use a separate set of rules for each page, but if you want to stick with this approach, this will work for your example:

$("#contactForm").validate( {
    rules: {
        name: {
            required: true
        },
        phone: {
            required: true
        },
        subject: {
            required: page === "contactJoe"
        },
        email: {
            required: true,
            email: true
        }
    }
});

Edit @ OP comment

How would I do this if the subject needs to appear for multiple pages?

subject: {
    required: page === "a" || page === "b" || page === "c"
}

// or
var subjectRequiredPages = ["a", "b", "c"];
// ...
subject: {
    required: $.inArray(page, subjectRequiredPages) !== -1
}

// or
var subjectPages = {a: true, b: true, c: true};
// ...
subject: {
    required: subjectPages[page]
}


What if you had a method called

    function SetupValidation(options){
        var defaults = {<defaults for program>};
        var settings = $.extend({}, defaults, options);
        return settings;
    }

Then each page could call SetupValidation with whatever it needed (phone, email etc) and you could have your "base" page use the settings value returned from this method.

This will take your default options and merge whatever options you pass in.

For example, if Phone is a default set to "true" and you pass in "False" it will change to False.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜