Validates that at least one checkbox is checked.
import { isCheckbox } from '@andresclua/validate'
const checkboxes = document.querySelectorAll('.c--form-checkbox-a__item')
const config = { minRequired: 1 }
// On Change
checkboxes.forEach(cb => {
cb.addEventListener('change', () => {
const result = isCheckbox({ elements: checkboxes, config })
errorEl.textContent = result.isValid ? '' : result.errorMessage
})
})
// On Submit
validateBtn.addEventListener('click', () => {
const result = isCheckbox({ elements: checkboxes, config })
errorEl.textContent = result.isValid ? '' : result.errorMessage
})
<div class="c--form-group-a">
<div class="c--form-checkbox-a">
<input type="checkbox" id="item-1" class="c--form-checkbox-a__item">
<label class="c--form-checkbox-a__title" for="item-1">JavaScript</label>
</div>
<div class="c--form-checkbox-a">
<input type="checkbox" id="item-2" class="c--form-checkbox-a__item">
<label class="c--form-checkbox-a__title" for="item-2">CSS</label>
</div>
<span class="c--form-error-a"></span>
</div>
/* Orientative — feel free to adapt to your own conventions */
.c--form-group-a {
margin-bottom: 1.5em;
}
.c--form-checkbox-a {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 0.5em;
}
.c--form-checkbox-a__item {
width: 16px;
height: 16px;
cursor: pointer;
accent-color: currentColor;
}
.c--form-checkbox-a__title {
font-size: 1em;
cursor: pointer;
}
.c--form-error-a {
color: red;
font-size: 0.875em;
display: none;
}
.c--form-error-a:not(:empty) { display: block; }
minRequired number Minimum number of checkboxes required to be checked. Default: 1
On Change
On Submit