diff --git a/app/javascript/controllers/evaluation_form_controller.js b/app/javascript/controllers/evaluation_form_controller.js index 9e08b9a8..0113cfef 100644 --- a/app/javascript/controllers/evaluation_form_controller.js +++ b/app/javascript/controllers/evaluation_form_controller.js @@ -73,28 +73,39 @@ export default class extends Controller { validatePresence(e) { const target = e.target; const formGroup = target.closest(".usa-form-group"); - const fieldName = target.dataset.fieldName; + const fieldName = target.dataset.fieldName || target.id; + const label = this.findLabel(target, formGroup); + + if (!target.value) { + this.addErrorClasses(target, label); + this.updateErrorMessage(fieldName, "can't be blank"); + } else { + this.removeErrorClasses(target, label); + this.updateErrorMessage(fieldName, ""); + } + } + + findLabel(target, formGroup) { const isSelect = target.tagName === "SELECT" || target.classList.contains("usa-combo-box__input"); - const isRadio = target.type === "radio"; const labelId = isSelect ? target.name : target.id; const labelQuery = isRadio ? "legend" : `label[for="${labelId}"]`; - const label = formGroup.querySelector(labelQuery); + return formGroup.querySelector(labelQuery); + } - if (!target.value) { - target.classList.add("border-secondary"); - if (label) label.classList.add("text-secondary"); - this.updateErrorMessage(fieldName || target.id, "can't be blank"); - } else { - target.classList.remove("border-secondary"); - if (label) label.classList.remove("text-secondary"); - this.updateErrorMessage(fieldName || target.id, ""); - } + addErrorClasses(target, label) { + target.classList.add("border-secondary"); + if (label) label.classList.add("text-secondary"); + } + + removeErrorClasses(target, label) { + target.classList.remove("border-secondary"); + if (label) label.classList.remove("text-secondary"); } updateErrorMessage(field, message) {