5

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>
2
  • it would have been really helpful if you had been much clearer in what you were expecting as an answer Commented Sep 19, 2013 at 15:42
  • 1
    You should also show your .validate() code. Commented Sep 19, 2013 at 15:42

2 Answers 2

5

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();
            }
        }
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

You should be able to condense it all down by replacing the entire if/else. Example: return !($('[name="myradiogroup"]:checked').length);
@Sparky excellent point! I think it can be made even shorter with dependency strings (you can provide a selector to match) but I can't get that to work... and I have real work to do at the office today, so I'll leave it at that. :)
I've had mixed results using the depends method.
-2

maybe can this:

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

1 Comment

Is'nt michbeck looking for jquery validation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.