I'm trying to validate a group of checkboxes where at least one is required. This is the HTML of my checkboxes:
<fieldset class="requiredcheckboxgroup">
<legend>How did you come into contact with VK?*</legend>
<input ng-model="application.contact.relations" group-required required type="checkbox" name="appcontact" value="relations" id="app-contact-relations" />relations<br>
<input ng-model="application.contact.employees" group-required required type="checkbox" name="appcontact" value="employees" id="app-contact-employees" contact-employees />employees<br>
<input ng-model="application.contact.employeesWho" type="text" placeholder="Who?" name="appcontact-employeeswho" id="app-contact-employees-who" disabled />
<input ng-model="application.contact.jobad" group-required required type="checkbox" name="appcontact" value="jobad" id="app-contact-jobad" />jobad<br>
<input ng-model="application.contact.website" group-required required type="checkbox" name="appcontact" value="website" id="app-contact-website" />website<br>
<input ng-model="application.contact.other" group-required required type="checkbox" name="appcontact" value="other" id="app-contact-other" />other<br>
</fieldset>
As you can see all of my checkboxes have the required attribute and the group-required attribute. I have a directive like this:
angular.module('dxs-vkgroupApp').directive('groupRequired', group_required);
function group_required() {
return {
restrict: 'A',
link: function(scope, element, attr) {
var requiredCheckboxes = jQuery('.requiredcheckboxgroup :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
}
};
}
The problem is that they all have to be selected before the form is valid... . The required attribute is correctly removed when one is selected but when I try to submit the form he still isn't valid.
How could I fix this? Or is there a better way to solve this?
You can try creating a function that determines if any checkbox has been selected:
And then on your html: