Sunday, January 8, 2012

Advanced jQuery Form validation (4): Display error message for grouped fields

After having discovered conditional triggers and learnt more about where to display error messages, we are going to display an error message for a group of fields.

In that example, two fields are related and at least one of them is required. In other words, each of those two fields is required if the other is empty. These two fields can be of any type, but we'll focus here on an input text and a textarea. Of course, we could have used a radio button to indicate that specific behavior, but we would like to keep it simple on the interface and limit the number of form elements.

The form is pretty straightforward. We set a div around the two related fields in order to display the error message after the both of them. Ideally, some CSS styling should be used to visually make clear that those two fields are related.
<form id="myFormId" method="post">
    <div id="groupDiv">
        <label for="textFieldId">One line text</label>
        <input type="text" name="textField" id="textFieldId" value="" /><br/>
        <label for="textAreaId">Many lines text</label>
        <textarea name="textArea" id="textAreaId"></textarea>
    </div>
    <input type="submit" value="Submit" />
</form>
The form validator defines oneOfTwo as a grouped element comprising both the input text and the textarea elements. The rules, messages and errorPlacement keys are nevertheless using the elements names separately.
$("#myFormId").validate({
        groups: {
            oneOfTwo: "textField textArea"
        },
        rules: {
            textField: { required: function() { return ($("#textFieldId", "#myFormId").val().length == 0); } },
            textArea: { required: function() { return ($("#textAreaId", "#myFormId").val().length == 0); } }
        },
        messages: {
            textField: 'Please enter either a one line text or copy/paste your text in the textarea.',
            textArea: 'Please enter either a one line text or copy/paste your text in the textarea.'
        },
        errorPlacement: function(error, element) {
            if ((element.attr("name") == "textField") || (element.attr("name") == "textArea")) {
                error.insertAfter("#groupDiv", "#myFormId");
            }
            else {
                error.insertAfter(element);
            }
        }
});

Validation de formulaire jQuery avancée (4) : affichage d'un message d'erreur pour des champs groupés (in French)
Validación de formulario jQuery avanzado (4): mostrar un mensaje de error para campos agrupados (in Spanish)
Validação de formulário jQuery avançado (4): a mostra de uma mensagem de erro para campos agrupados (in Portuguese)

No comments:

Post a Comment