I have form Array , which controls has to be required , based on a variable ,now I wrote custom validator like below
recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return Validators.required;
}
return null;
};
}
now this will check the value of the 'myVariable' and put required but somehow its not working , I am adding this custom validators like below
const fbGroup = this.fb.group({
recurringControl1: this.fb.control('', [this.recurringValidator()]),
recurringControl2: this.fb.control('', [this.recurringValidator()]),
recurringControl3: this.fb.control('', [this.recurringValidator()])
});
this.myForm = this.fb.group({
control1: fb.control('', [this.recurringValidator()]),
groupcontrol1: fb.array([])
});
when I click on submit , form is valid when even myVariable
value is 'constant1'
.
any suggestion or modifications please .
here is the stackblitz link https://stackblitz.com/edit/angular-form-array-validators?
You are passing the validator reference instead of executing and returning the value. If you were to use the validator directly, that would be the correct way to do it, but since you are using your custom validator, the validator will be called by Angular (your validator) but for the required validator, you are the one who need to invoke it, so try replacing:
recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return Validators.required;
}
return null;
};
}
To:
recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
// if (!control.value) {
// return null;
// }
if (this.myVariable === 'constant1') {
// Invoking the validator ourselves
return Validators.required(control);
}
return null;
};
}
Also, I don't see the need for the first condition !control.value
, that will always return null for empty values no matter the content of myVariable
, so I commented out.