Skip to content

Commit

Permalink
296 Simplify validate presence function
Browse files Browse the repository at this point in the history
  • Loading branch information
cpreisinger committed Dec 17, 2024
1 parent 120a70a commit ea655eb
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions app/javascript/controllers/evaluation_form_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit ea655eb

Please sign in to comment.