Saturday, November 19, 2011

Advanced jQuery Form validation (3): Add conditional requirement rule for a set of checkboxes

The third article of that series about advanced jQuery Form validation deals with conditional triggers. In that particular case, we have a conditional trigger displayed as a radio button that makes a set of checkboxes required when activated, and optional when not activated.

All the checkboxes share the same name checkBoxesName[]. Note the square brackets, as we handle them with PHP on the server side, and the grouping has to be done this way.
To apply a validation rule to the set of checkboxes, the square brackets have to be used, hence the simple quotes used to delimitate their name in form validator set of rules.

As the checkboxes are required only if the conditional trigger is activated, that condition is rendered as a function in the required parameter of the matching rule. That function returns True if the radio button which id is conditionalTriggerActivatedId is checked, and False otherwise.
As long as this function returns a boolean, it can handle very complex algorithms, such as a cascading set of fields with specific values rendered as a very complex boolean expression (your imagination, or rather the form's complexity, is the only limit here).

The form id used as second parameter in the boolean expression $("#conditionalTriggerActivatedId", "#myFormId").attr("checked") is known as its context. It tells jQuery in which context to find the element of id conditionalTriggerActivatedId, i.e. it will search for it within the scope of the element of id myFormId. This is a good way to accelerate the processing, and the closest the context to the parameter element, the better.

<form id="myFormId" method="post">
    <div id="conditionalTriggerDiv">
        <input type="radio" name="conditionalTrigger" id="conditionalTriggerActivatedId" value="y" checked="checked" />Conditional Trigger Activated<br/>
        <input type="radio" name="conditionalTrigger" id="conditionalTriggerNotActivatedId" value="n" />Conditional Trigger Not Activated<br/>
    </div>
    <div id="conditionalTriggerActivatedDiv">
        <input type="checkBox" id="checkBoxesIdOne" name="checkBoxesName[]" value="1" />First checkBox<br/>
        <input type="checkBox" id="checkBoxesIdTwo" name="checkBoxesName[]" value="2" />Second checkBox<br/>
        <input type="checkBox" id="checkBoxesIdThree" name="checkBoxesName[]" value="3" />Third checkBox<br/>
    </div>
    <input type="submit" value="Submit" />
</form>
$(document).ready(function(){
    $("#myFormId").validate({
        rules: {
            'checkBoxesName[]': {
                required: function() {
                            return $("#conditionalTriggerActivatedId", "#myFormId").attr("checked");
                        }
            }
        }
    });
});
But if we stop the code here, the error message of the required set of checkboxes will be displayed right after the first checkbox, that is to say between the first checkbox and its label.
The errorPlacement key is used to tell where to display the error message. It will now display the error message for the checkboxes after their containing div, and any other error message after the element as by default.

$("#myFormId").validate({
    rules: {
        'checkBoxesName[]': {
            required: function() {
                        return $("#conditionalTriggerActivatedId", "#myFormId").attr("checked");
                    }
        }
    },
    errorPlacement: function(error, element) {
        if (element.attr("name") == "checkBoxesName[]") {
            error.insertAfter("#conditionalTriggerActivatedDiv", "#myFormId");
        }
        else {
            error.insertAfter(element);
        }
    }
});


Validación de formulario jQuery avanzado (3): añadir una regla condicional a un conjunto de casillas de verificación (in Spanish)
Validation de formulaire jQuery avancée (3) : ajouter une règle conditionnelle à un ensemble de cases à cocher (in French)
Validação de formulário jQuery avançado (3): adicionar uma regra condicional à um conjunto de caixas de seleção (in Portuguese)

No comments:

Post a Comment