5

I am using the Validation Plugin for jQuery and it works wonders. Except when I have a group of checkboxes...the error messages will display right after the first checkbox...like so:

alt text

<tbody>
     <c:forEach items="${list}" var="item">
        <tr>
          <td align="center">
             <input type="checkbox" name="selectItems" value="<c:out value="${item.numberPlate}"/>" />
          </td>
          <!--some other columns-->
         </tr>
      </c:forEach>                       
</tbody>

------------------------------EDITED-------------------------

I found that I can use errorPlacement , but I have no idea how to show ONLY the error message of the checkbox array in the table footer or somewhere else inside the second fieldset.

Hope you can help me out.

2 Answers 2

7

Why not use a custom validation method ? Something like this:

jQuery:

// The custom validation method, returns FALSE (invalid) if there are
// no checkboxes (with a .one_required class) checked
$.validator.addMethod("one_required", function() {
    return $("#myform").find(".one_required:checked").length > 0;
}, 'Please select at least one vehicle.');

$("#myform").validate({
    // Use the built-in errorPlacement function to place the error message
    // outside the table holding the checkboxes if they are the ones that
    // didn't validate, otherwise use the default placement.
    errorPlacement: function(error, element) {
        if ($(element).hasClass("one_required")) {
            error.insertAfter($(element).closest("table"));
        } else {
            error.insertAfter(element);
        }
    }
});

HTML:

<form id="myform">
    <!-- table, rows, etc -->
    <td align="center"><input type="checkbox" class="one_required" name="selectItems[]" value="NA245852" /></td>
    <td>NA245852</td>
    <!-- more rows, end table, etc -->
    <br/>
    <input type="submit" value="Go, baby !">
</form>

Since the jQuery Validate plugin can also validate an element if the method name is present as a class, simply output the .one_required class on all checkboxes.

See a working demo on JSFiddle with multiple checkboxes.

EDIT:

Here's your own code with the above solution implemented.

Hope this helps !

Sign up to request clarification or add additional context in comments.

5 Comments

I don't know how to thank you , FreekOne and Cybernate, you both have been so supportive :D
@eddy - Glad to be of help ! :)
You do not need a custom method to validate a group of checkboxes. Your custom method is no different than the default required rule.
@Sparky Indeed, you are correct on your first point. I was not aware back then that one can validate a group of checkboxes that require at least one to be checked by using the array notation in the name attribute (even though I see that I had that in my fiddle, weird). On your second point however, I believe the difference is obvious: the custom method does not require said array notation, not that there's anything wrong with it. TL;DR: people should use the array notation along with the default required method instead :)
As long as every checkbox in the group has the same name, it absolutely does not matter that the name contains a [] at the end.
2

You can use errorLabelContainer configuration option.. define a div with an id like errorMessages and then change your validate method call as follows:

$("form").validate({
   errorLabelContainer: $("#errorMessages"),
     rules: ..... your rules

Now all the error messages will be displayed in the div. Edit: Updated the answer below to reflect the updates to the question: To change the location of error messages displayed, I can think of using the errorPlacement config parameter. You can use something like: Define a div or a p and keep appending the messages for the checkboxes to this element.

$("form").validate({
errorPlacement:function(error,element) {
    if (element.attr("name") == "selectItems") {
        //Add Code to append the error message to a predefined element
        $("#errorDiv").html("");
        $("#errorDiv").append("<YOUR_CUSTOM_MESSAGE>");
    } else { 
        error.insertAfter(element);
    }
  },
  rules: ..... your rules
});

jsFiddle URL: http://jsfiddle.net/Z8hWg/28/

EDIT: Change your javascript to as follows:

<script type="text/javascript">
    $(document).ready(function(){        
                var formValidator = {};
                $("#Date").datepicker();       
                formValidator = $("#form1").validate({
                        errorPlacement:function(error,element) {
                                if (element.attr("name") == "selectedItems") {
                                                //Add Code to append the error message to a predefined element
                                        $("#errorDiv").html("Select at least one vehicle");
                                } else {
                                        error.insertAfter(element);
                                }
                        },

                        rules: {
                                avgTime:{
                                        required:true,
                                        number:true
                                },

                                selectedItems:
                                {
                                        required:true
                                },
                                Date:{
                                        required:true,
                                        date:true
                                }

                        },    
                        //onclick: true,
                        submitHandler: function(form) {
                                $("#errorDiv").html("");
                                form.submit();
                        }

                });       
                $("input[name=selectedItems]").bind("change", function() {
                        var me = $(this);
                        var scoper = me.parent().parent();
                        var otherInputs = $("input[name^=mileage]", scoper);
                        otherInputs.attr("disabled", !this.checked);
                        otherInputs.attr("value","");
                        if (this.checked)
                        {
                                otherInputs.addClass('required number');
                                $("#errorDiv").html("");
                        }
                        else
                        {
                                otherInputs.removeClass("required number");
                        }
                        formValidator.element("input[name=selectedItems]");
                });


        });  
</script>

12 Comments

@Cybernate: Thank you, but as you say by using the errorLabelContainer all the error messages will be displayed in the same place and that's not what I need since I have two different sections in my form. I updated the image in my question to show how my whole form looks
@Cybernate: it does add the error message, but it does it for every single element of the array :( and ... it doesn't remove the error message when all the rules are met :(
You can define submitHandler in the validation configuration and reset the div. e.g submitHandler: function(form) {$("#errorDiv").html(""); form.submit(); }
@Cybernate- I tried what you told me, but the problem persists: If I have 5 check boxes, every time I click on one of them, either to check it or uncheck it, a new error message appears on the div
Can you post the HTML at jsFiddle.net?
|

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.