0plus1
0plus1

Reputation: 4555

Validating inputs that share the same name

I'm using a method as explained here: http://iamcam.wordpress.com/2008/01/15/unchecked-checkbox-values/ to get a value even if the checkbox is left unchecked, I won't go into details about why I need this but it's a necessity. That being said..

All this wonderful method is part of an abstraction layer for form that I've written myself, I have a couple of checkboxes that I whish to get validated by jquery validate, the problem is that the html is like this:

<input class="" type="hidden" value="0" name="check[legal]">
<input id="legal" class="required" type="checkbox" name="check[legal]" value="1">

What happens is that jquery validate validates the first input of the two (since they have both the same name. I understand that I can simply remove the first one and be done with it, I just want to know if there is any way to validate the second checkbox leaving everything as it is (I can see two roads here: 1) validate from the id of the input 2) exclude hidden elements from validation, even if I think that that way it will avoid even the second one for having the same name..)

Upvotes: 2

Views: 1306

Answers (1)

Kato
Kato

Reputation: 40582

Okay, the direct answer to your question is that you can define a custom validate method as shown in this example. Here is the critical code:

$.validator.methods.checkLegal = function(value, element) {
    return $('input[type=checkbox][name="check[legal]"]').attr('checked');
}

$('form').validate({
    rules: { "check[legal]": {checkLegal: true} },
    messages: { "check[legal]": "You must check the box" },
});

However, your fields don't need to have the same name to use the principle described in the link you provided. In fact, it will simplify things greatly if you don't. It is also unclear why you need braces in the variable names if this is not a checkbox list.

That said, here is a simple example that does not use the same names, stores the hidden value, and validates the visible checkbox. The replacement for the above being:

jQuery(function($) {
    $('form').validate({
        rules: { "check[legal]": "required" },
    });

    $('#legal').click(function(e) {
        $('#legalHidden').val($(this).attr('checked') ? 1 : 0);
    });

});

On the server, you would simply reference check[legalhidden] and not bother with check[legal]. On the client, all validation is done on check[legal] and the value is copied into the legalhidden var each time it is clicked.

Upvotes: 3

Related Questions