How to add a conditional validator for reactive forms in Angular

Conditional Validation

Our requirement is that when notification is set to phone then the phonenumber FormControl should be a required field and if it is set to email then phonenumber FormControl should not have any validation.

formValueChanged() {

    const shipAddress= this.loginForm.get('shipAddress');
    this.loginForm.get('notification').valueChanges.subscribe(
        (mode: string) => {
            console.log(mode);
            if (mode === 'phone') {
                shipAddress.setValidators([Validators.required]);
            }
            else{
                shipAddress.clearValidators();
            }
            shipAddress.updateValueAndValidity();
        });

}

Calling method

Calling the formValueChanged method in the ngOnInit should now look like this:

ngOnInit() {
   this.loginForm = this.fb.group({
        name: [null, Validators.required],
        billAdrresss: [null, [Validators.required, Validators.maxLength(8)]],
        isShipDiffrent: [false],
        shipAddress: [null]
    });
   this.formValueChanged();
  }

Leave a Reply

Your email address will not be published. Required fields are marked *