[jQuery] [validate] Test that at least one input element has value

[jQuery] [validate] Test that at least one input element has value


I have a product listing where the user can enter the required
quantity of each product. The setup is something like this:
<form>
<ul>
<li><label for="name">Name</label><input name="name" id="name" /></
li>
<li><label for="address">Address</label><input name="address"
id="address" /></li>
...
<li><input class="quantity" name="product1" />Product1</li>
<li><input class="quantity" name="product2" />Product2</li>
<li><input class="quantity" name="product3" />Product3</li>
<li><input class="quantity" name="product4" />Product4</li>
...
<li><input type="submit" value="Place order" /></li>
</ul>
</form>
<p class="message">
It doesn't make sense to accept an order without any products. So I
want to make sure that at least one of the product inputs has a value,
and display an error message if that's not the case. I've made an
attempt here:
if( $(".quantity:input:filled").length == 0 ){
$(".message").text("Please select at least one!");
}
This is evaluated each time the page is loaded, but I'd like to do
this when the rest of the form is validated. I tried using addMethod
to add a custom validation method like this:
$.validator.addMethod("cAtLeastOne", function() {
if( $(".quantity:input:filled").length == 0 ){
return 0;}
else {
return 1;}
}, "Please select at least one!");
$.validator.addClassRules("quantity", { cAtLeastOne: true });
This places the error message after all the product input fields, and
when a value is entered in one input it doesn't clear the other error
messages (but they're cleared on submit).
Does anyone have suggestions to how this can be done correctly?
Thanks in advance!