JSFiddle - React, Tailwind, and code Playground
HTML
<form method="post">
<input type="checkbox" name="cb[]"/>
<input type="checkbox" name="cb[]"/>
<input type="checkbox" name="cb[]"/>
<button>Submit</button>
</form>
JavaScript
var checkListe = document.querySelectorAll('[name="cb[]"]');
var checkArray = Array.prototype.slice.call(checkListe);
checkArray.forEach(function(checkbox){
validateAll();
checkbox.addEventListener('input', validateAll);
checkbox.addEventListener('change', validateAll);
});
function validateAll () {
checkArray.forEach( validate );
}
function validate (checkbox) {
var markierteCheckboxen = document.querySelectorAll(':checked');
checkbox.setCustomValidity('');
checkbox.classList.remove('too-view-error');
checkbox.classList.remove('too-many-error');
debugger;
if (!checkbox.checked && markierteCheckboxen.length < 2) {
checkbox.setCustomValidity('Sie müssen noch eine weitere Option auswählen');
checkbox.classList.add('too-view-error');
} else if (checkbox.checked && markierteCheckboxen.length > 2) {
checkbox.setCustomValidity('Sie haben zu viele Optionen gewählt');
checkbox.classList.add('too-many-error');
}
}