qinking126
qinking126

Reputation: 11915

How to use JQuery validation plugin with conditions?

I am using JQuery validation plugin to validate my form.

I have a radio button on the top. if you pick "yes", some input fields will show up. if you pick "no", different input fields will be used.

How do I change my validation codes, so It will validate those fields based on the radio button?

Upvotes: 1

Views: 92

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

This is pretty simple if you're just worried about required fields. You can supply a dependency for the required rule:

$("#test").validate({
    rules: {
        Yes1: {
            required: "#yes:checked"
        },
        Yes2: {
            required: "#yes:checked"
        },
        No1: {
            required: "#no:checked"
        },
        No2: {
            required: "#no:checked"
        }
    }
});

Example: http://jsfiddle.net/andrewwhitaker/7SYcE/

Now, this gets more complicated if you're using other rules. I will expand my answer if this isn't powerful enough for you.

Upvotes: 1

Related Questions