Skip to content

Commit 978a160

Browse files
Merge pull request #1591 from lucasnetau/fix/1565
fix: ensure that other value is required when other option is selected for radio and checkbox groups
2 parents 7cdc8ac + 457a3e3 commit 978a160

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/js/control/select.js

+18-7
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export default class controlSelect extends control {
3333
data.name = data.name + '[]'
3434
}
3535

36-
if (type === 'checkbox-group' && data.required) {
36+
if ((type === 'checkbox-group' || type === 'radio-group') && data.required) {
3737
const self = this
3838
const defaultOnRender = this.onRender.bind(this)
3939
this.onRender = function() {
@@ -153,7 +153,10 @@ export default class controlSelect extends control {
153153
* setCustomValidity for checkbox-group
154154
*/
155155
groupRequired() {
156-
const checkboxes = this.element.getElementsByTagName('input')
156+
const allInputs = this.element.getElementsByTagName('input')
157+
const checkboxes = this.element.querySelectorAll('input:not([type=text])')
158+
const otherCheckbox = this.element.querySelector('.other-option')
159+
const otherValue = this.element.querySelector('.other-val')
157160
const setValidity = (checkbox, isValid) => {
158161
const minReq = control.mi18n('minSelectionRequired', 1)
159162
if (!isValid) {
@@ -162,24 +165,32 @@ export default class controlSelect extends control {
162165
checkbox.setCustomValidity('')
163166
}
164167
}
165-
const toggleRequired = (checkboxes, isValid) => {
166-
[].forEach.call(checkboxes, cb => {
168+
const toggleRequired = (checkboxes, otherCheckbox, otherValue, isValid) => {
169+
[].forEach.call(checkboxes, cb => {
167170
if (isValid) {
168171
cb.removeAttribute('required')
169172
} else {
170173
cb.setAttribute('required', 'required')
171174
}
172175
setValidity(cb, isValid)
173176
})
177+
178+
if (otherCheckbox) {
179+
if (otherCheckbox.checked) {
180+
otherValue.setAttribute('required', 'required')
181+
} else {
182+
otherValue.removeAttribute('required')
183+
}
184+
}
174185
}
175186

176187
const toggleValid = () => {
177188
const isValid = [].some.call(checkboxes, cb => cb.checked)
178-
toggleRequired(checkboxes, isValid)
189+
toggleRequired(checkboxes, otherCheckbox, otherValue, isValid)
179190
}
180191

181-
for (let i = checkboxes.length - 1; i >= 0; i--) {
182-
checkboxes[i].addEventListener('change', toggleValid)
192+
for (let i = allInputs.length - 1; i >= 0; i--) {
193+
allInputs[i].addEventListener('change', toggleValid)
183194
}
184195
toggleValid()
185196
}

0 commit comments

Comments
 (0)