Form fields validation only if visible

Hi, I can validate form by the help of FormBuilder and FormControl as below

>  this.myForm = this.formBuilder.group({
>       Description: new FormControl('', Validators.required),
>       PerHour: new FormControl('',Validators.required))
>  })

But I want to validate field PerHour only if this is visible.
PerHour is visible when I click on radio button.

Means; validate only if flag is true.

How can I do this?

Validators can be changed at any time using setValidators.

@rapropos, thanks for reply. I made changes as per your suggestion as below:-

//Custom form validation

this.pricePerHour = false/true;  //based on visible or not
this.bidForm = this.formBuilder.group({
      Description: new FormControl('', Validators.required),
      PerHour: new FormControl('', Validators.compose([this.PriceValidator(this.pricePerHour)]))
     //this.pricePerHour is a boolean variable, initially false
    });
priceValidator(argPerHour: boolean): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      console.log(argPerHour); 
     // always false even on true
      if (control.value == '' && argPerHour == true) {
        return { valid: true };
      }
      return null;
    };
    }

Here I want to validate PerHour only if pricePerHour is true.

In this case form is checking PerHour field either pricePerHour is false or true (visible/disable).
Means boolean variable pricePerHour is always false inside priceValidator().

I also check with below but did not work:-

   this.myForm = this.formBuilder.group({
   Description: new FormControl('', Validators.required),
   PerHour: new FormControl('', Validators.compose([this.pricePerHour ==    
     true ? null : Validators.required]))
   });

The way you’ve written this, the value of pricePerHour is locked in at the time that priceValidator is called. So you’re fighting the flow a bit. What I would suggest is adding/removing the validator at the time pricePerHour changes.

@rapropos Thanks for advice, I will check on this.

@rapropos You saved my day.

This was so simple and I made this so complex. I just add below lines where I was calling change function. Solved :slight_smile:

this.bidForm.get('PerHour').setValidators([Validators.required]);
this.bidForm.get('PerHour').updateValueAndValidity();
1 Like