Search code examples
angularvalidationangular-validation

Validate same value on two selects in Angular 9


I'm new to Angular, it's another programmer's code actually. Any ideas or would be really appreciated.

I have two simple selects with three options and I'm trying to validate that they have the same value selected.

I created a validator which checks if the second select has the same value as the first. It works just for the second, but when I change the first select, the validator doesn't run or update.

The code looks like this:

  maxTimeValidator = ( control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if ( control.value !== this.RiskForm.controls.range_min_time.value ) {
      return { differentTimeRange: true, error: true };
    }

    return {}
  }


  RiskForm: FormGroup;
  submit_error = false;
  RiskData = {
    id: [null,[]],
    range_min_time: [null, [Validators.required]],
    range_max_time: [null, [Validators.required,this.maxTimeValidator]],
  }

  ngOnInit(): void {
    // Initialice Form Data
    this.RiskForm = this.formBuilder.group(this.RiskData);
  }

I tried createing two validation functions / same problem: validator doesn't seem to run or update when changing one select.

Any advice would be helpful, I appreciate that you take your time for helping.


Solution

  • You would need a validator that will apply on your form. Similar to this:

    this.registerForm = this.formBuilder.group(
      {
        firstName: ["", [Validators.required]],
        lastName: ["", [Validators.required]],
        email: ["", [Validators.required, Validators.email]],
        password: ["", [Validators.required, Validators.minLength(6)]],
        confirmPassword: ["", Validators.required]
      },
      {
        // Used custom form validator name
        validator: ComparePassword("password", "confirmPassword")
      }
    );
    
    
    export function ComparePassword(controlName: string, matchingControlName: string) {
          return (formGroup: FormGroup) => {
            const control = formGroup.controls[controlName];
            const matchingControl = formGroup.controls[matchingControlName];
    
            if (matchingControl.errors && !matchingControl.errors.mustMatch) {
              return;
            }
    
            if (control.value !== matchingControl.value) {
              matchingControl.setErrors({ mustMatch: true });
            } else {
              matchingControl.setErrors(null);
            }
          };
    }