JQuery Validate Plugin: make input required depending on radio button value
I'm having a real headache trying to get the jQuery Validate plugin to work.
I have a form, the first question asking the user to select an option from a radio group. This shows further questions below, depending on their selection.
What I'm trying to achieve is making the v开发者_Go百科isible questions required, but obviously depending on what the user chose at the first question - ie. if the question isn't visible then don't require it.
The form can be seen here: http://planner.adamturtle.com/index.php?id=cab11f902671b3c2d6&page=2
All the javascript code is embedded on the page.
Thanks for your help.
To gather visible elements:
$currentInputs = $("input:visible");
What I would do for readability purposes is assign all "active" inputs to be validated with a class like "validateMe":
$currentInputs = $("input.validateMe");
$result = $currentInputs.validate();
jQuery validate plugin allows you to add a custom validation methods and you may want to try those. Inside this method you can check when is the value of the radio box and check other field values based on that information.
The method to add a custom validation is called addMethod
(docs link here).
If all questions are required - no matter what - you could probably just validate all fields.
But this would only work if you used some kind of ajax call to populate the forms. This way it's not trying to validate the questions that are not displayed.
Ex: have a string that contains the HTML you'd like to embed.
var formString1 = '<input type="text" name="thisInput" />';
formString1 = '<input type="radio" name="anotherInput" />;
...
and then inject each form string into the given forms.
OR
send out a request to validate the forms with class="required"
. Which you can add depending on which radio button is clicked.
jQuery:
validate($(.required));
function validate(elements){
$.ajax( //send request to validate 'elements );
}
It's a bit dirty, doesn't use the form validator plug-in and none of these are tested, but it might give you some direction.
EDIT: Do you have a set system for the PHP backend validation?
精彩评论