michbeck
michbeck

Reputation: 745

conditional form validation using jquery.validate.js plugin

Can anyone tell me how to write a rule that validates if neither one radio button option nor the (optinal) textfield is chosen/filled by a user? The rule should only give a message if no checkbox option #myradiogroup is chosen AND the textfield #email2 is empty.

My form code:

<form name="my" id="myForm" action="" method="post">

<input type="radio" name="myradiogroup" id="myradiogroup" value="option 1" /> option 1
<input type="radio" name="myradiogroup" id="myradiogroup" value="option 2" /> option 2

<label for="emailNew4use">this is an optional field:</label>
<input type="text" name="email2" id="email2" />

<input type="submit" value="send">

</form>

Upvotes: 5

Views: 8097

Answers (2)

Evan Davis
Evan Davis

Reputation: 36592

The required parameter in jQuery Validate can take a function.

$('#myForm').validate({
    rules: {
        email2: {
            required: function(element) {
                if ($('[name="myradiogroup"]:checked').length) {
                    return false;
                } else {
                    return true;
                }
            }
        },
        myradiogroup: {
            required: function(element) {
                if ($('#email2').val()) {
                    return false;
                } else {
                    return true;
                }
            }
        }
    }
});

Here's a condensed version from Sparky

$('#myForm').validate({
    rules: {
        email2: {
            required: function(element) {
                return !$('[name="myradiogroup"]:checked').length;
            }
        },
        myradiogroup: {
            required: function(element) {
                return !$('#email2').val();
            }
        }
    }
});

Upvotes: 5

Striver
Striver

Reputation: 1

maybe can this:

$('#myForm').submit(function() {
    if($('input:radio').val() == '' || $('#email2').val() == '') {
        preventDefault();
        // show error
    }
}

Upvotes: -2

Related Questions