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.