added support for setting a minimum number of selections in a check group
This commit is contained in:
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user