To set Validation And retain the error in the required field

42 Views Asked by At

I have three input fields: two dropdowns and one slider number field. In my custom validation, I utilize the form control names as strings within the service field to capture the value changes of the form controls. While this approach works seamlessly, upon page load, it fails to retain focus in the required field as expected.

I have attempted various methods to retain focus in the field, but none have proven successful.

import { AbstractControl, FormGroup, ValidatorFn } from "@angular/forms";
validateActiveHoursStartEndTimes(maximumActiveHoursKey: string, activeHoursStartTimeKey: string, activeHoursEndTimeKey: string): ValidatorFn {
  let lastChangedControl: AbstractControl;

  return (group: FormGroup): { [key: string]: unknown } | null => {
    group.controls[activeHoursStartTimeKey]?.valueChanges.subscribe(() => {
      lastChangedControl = group.controls[activeHoursStartTimeKey];
      updateValidation(group);
    });

    group.controls[activeHoursEndTimeKey]?.valueChanges.subscribe(() => {
      lastChangedControl = group.controls[activeHoursEndTimeKey];
      updateValidation(group);
    });

    group.controls[maximumActiveHoursKey]?.valueChanges.subscribe(() => {
      lastChangedControl = group.controls[maximumActiveHoursKey];
      updateValidation(group);
    });

    return null;
  };
  function updateValidation(formGroup: FormGroup): void {
    const maximumActiveHours = formGroup.controls[maximumActiveHoursKey]?.value as number;
    const activeHoursStartTime = formGroup.controls[activeHoursStartTimeKey]?.value as number;
    let activeHoursEndTime = formGroup.controls[activeHoursEndTimeKey]?.value as number;

    if (activeHoursEndTime < activeHoursStartTime) {
      activeHoursEndTime += 24;
    }

    if (maximumActiveHours !== null && maximumActiveHours !== undefined) {
      if (activeHoursEndTime - activeHoursStartTime > maximumActiveHours) {
        clearErrorsExcept(formGroup, lastChangedControl);
        formGroup.controls[maximumActiveHoursKey]?.setErrors({ 'activeHoursOutOfRange': true });
      } else {
        clearErrorsExcept(formGroup, null);
      }
    }
  }
  function clearErrorsExcept(formGroup: FormGroup, exceptControl: AbstractControl | null): void {
    Object.values(formGroup.controls).forEach(control => {
      if (control !== exceptControl) {
        control.setErrors(null);
      }
    });
  }
}
0

There are 0 best solutions below