burzum burzum - 2 months ago 23
jQuery Question

jQuery Validate hidden field

I'm trying to validate the count of elements when a form is submitted via Jquery Validator. The reason is that we want at least one image to be present but we don't upload them directly but instead show a preview first. So I need to count them somehow and validate that at least one is present.

I've tried using a hidden field as described here but it is simply not working. The test field validates but for some reason my own rule doesn't even get triggered. What's wrong with my implementation?

The hidden field trick doesn't work any more, it's not validating hidden inputs anymore it seems.

<form method="post" accept-charset="utf-8" id="submit-work-form" role="form" action="/" novalidate="novalidate">
<div class="form-group">
<input type="text" required="true" name="title"/>
<input type="hidden" name="image_count" required="required" data-rule-validcmsimagecount="true" aria-required="true">
<div class="photos">
<!-- containers go here -->
</div>
</div>
<div class="submit"><input type="submit" class="btn btn-black btn-default" value="Submit"></div>
</form>


JS:

$.validator.addMethod("validcmsimagecount", function(value, element) {
alert('Doesn\'t work');
return $('.photo-container').length > 0;
}, "You must add at least one image.");

$('#submit-work-form').validate({
submitHandler: function (form) {
form.submit();
}
});


You can try the Jsfiddle as well.

Answer

This is probably a duplicate of this post but since I updated your fiddle to fix it, I thought I would post is as an answer. Looks like you need to enable the validation of hidden fields and remove the required attribute from the hidden field. Once done, the validation will run, see the updated fiddle here , the main change is the addition of the ignore property:

$('#submit-work-form').validate({
       ignore: [],
            submitHandler: function (form) {
                form.submit();
            }
        });