diff --git a/index.html b/index.html index 4d2590f..62f0de3 100644 --- a/index.html +++ b/index.html @@ -58,7 +58,8 @@
Check Group - + + diff --git a/validation.js b/validation.js index 58ab741..cf5f291 100644 --- a/validation.js +++ b/validation.js @@ -6,6 +6,7 @@ class ValidationField { labelText = null message = null messageOutputted = null + minCount = null optional = false pattern = null patternMessage = null @@ -93,6 +94,23 @@ class ValidationField { // add a native pattern attr if pattern property is present if (this.pattern) this.el.setAttribute('pattern', this.pattern) + // track minimum selections for checkboxes; todo: add multiple attr support + if (this.el.type === 'checkbox') { + if (!this.validationInstance.multi.hasOwnProperty(this.el.name)) { + this.validationInstance.multi[this.el.name] = {} + // this.validationInstance.multi[this.el.name].count = 0 + this.validationInstance.multi[this.el.name].minCount = this.minCount ?? 1 + } + + // if (this.el.checked) this.validationInstance.multi[this.el.name].count++ + + // this.el.addEventListener('change', () => { + // this.el.checked + // ? this.validationInstance.multi[this.el.name].count++ + // : this.validationInstance.multi[this.el.name].count-- + // }) + } + // add required indicator if (this.validationInstance.reqIndicators) { const hasIndicator = this.formGroupEl?.querySelector(`.${this.validationInstance.reqIndicatorClass}`) @@ -121,6 +139,7 @@ class Validation { form = null invalidClass = 'invalid' messageClass = 'invalid__message' + multi = [] onlyOnSubmit = false onSuccess = null passConfirm = true @@ -309,8 +328,12 @@ class Validation { } validateCheckbox(fieldInstance, nameAttrVal) { - if (!this.form.querySelector(`[name="${nameAttrVal}"]:checked`)) { - this.addError(fieldInstance, `At least one choice is required.`) + let messageMod = fieldInstance.validationInstance.multi[`${nameAttrVal}`].minCount === 1 ? `choice is` : `choices are` + let message = `At least ${fieldInstance.validationInstance.multi[`${nameAttrVal}`].minCount} ${messageMod} required.` + + if (this.form.querySelectorAll(`[name="${nameAttrVal}"]:checked`).length < + fieldInstance.validationInstance.multi[`${nameAttrVal}`].minCount) { + this.addError(fieldInstance, message) } }