'How to apply custom validator on Form group control

I have Root FormGroup that contains different different FormGroup .I want to apply validator on control between two or more FormGroup .

For Example:

I have to two FormGroup mobile and workPhone and each FormGroup has different controls such as number etc.

Now i have to write validator on both mobile and workPhone to become one optional on enter value in number control. for more refrence please see the example on stackblitz.

how to achieve this Initial both control will be required. But when I enter the work phone number, the mobile number should become optional And Vice Versa.

appcomponent.ts

import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
  ValidationErrors,
  ValidatorFn,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  rootForm!: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.rootForm = this.fb.group(
      {
        mobile: new FormGroup({
          countryCode: new FormControl('+1'),
          number: new FormControl('', [Validators.required]),
        }),

        workPhone: new FormGroup({
          countryCode: new FormControl('+1'),
          number: new FormControl('', [Validators.required]),
        }),
      },
      { Validators: EitherMobileOrWorkPhoneRequired }
    );
  }

  public onSubmit(value) {
    console.log('Form Invalid:' + this.rootForm.invalid);
  }
}

export const EitherMobileOrWorkPhoneRequired: ValidatorFn = (
  control: AbstractControl
): ValidationErrors | null => {
  console.log(control);
  return null;
};

If any other details required. Please let me know. Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source