Conditionally implement validation in form fields of an Angular 2 reactive form
The problem is that your code evaluates the expression just once - when the FormGroup
is created. You need to make it dynamic by creating your custom validator that will evaluate the expression every time it gets called:
this.personForm= this.fb.group({
firstName: ['', Validators.required];
lastName: [
'',
conditionalValidator(
(() => this.isValidationForLastName === true),
Validators.required
)
]
});
function conditionalValidator(condition: (() => boolean), validator: ValidatorFn): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
if (! condition()) {
return null;
}
return validator(control);
}
}
Another way of doing it would be something like this. Seems to work on plunker
ngOnInit() {
this.myForm = this._fb.group({
validateBy: ['byFirstName'],
firstName: [''],
lastName: [''],
});
this.myForm.get('validateBy').valueChanges.subscribe(
(validateBy : string) => {
if (validateBy === 'byFirstName' || validateBy === 'byBoth') {
this.myForm.get('firstName').setValidators([Validators.required]);
this.myForm.get('firstName').updateValueAndValidity();
}
if (validateBy === 'byLastName' || validateBy == 'byBoth') {
this.myForm.get('lastName').setValidators([Validators.required]);
this.myForm.get('lastName').updateValueAndValidity();
}
};
)
}