Background
Asynchronous validation on a FormGroup is only executed when all synchronous validation for that group and all of its children are valid.
Issue
I want to execute a asyncValidator on a FormGroup before all children are valid.
this.myForm = new FormGroup({
country: [ null, [ Validators.required ] ],
postalCode: [ null ],
unrelatedField1: [ null ],
unrelatedField2: [ Validators.min(123) ]
}, {
validators: [ postalCodeFormat ],
asyncValidators: [ postalCodeExists ]
})
My custom postalCodeExists validator needs the country and postalCode field. It doesn't care about the validity of 'unrelatedField2'.
Is there any way I can trigger the async validation of a FormGroup manually?
My first idea
As far as I know this is not possible.
this.myForm.valueChanges.pipe(
map(...etc),
distinctUntilChanges(...etc)
).subscribe(() => {
if (this.myForm.get('country').valid && this.myForm.get('postalCode').valid) {
this.myForm.executeAsyncValidationPlease();
}
});
My second idea
this.myForm = new FormGroup({
countryAndPostalCodeGroup: new FormGroup({
country: [ null, [ Validators.required ] ],
postalCode: [ null ],
}, {
validators: [ postalCodeFormat ],
asyncValidators: [ postalCodeExists ]
}),
unrelatedField1: [ null ],
unrelatedField2: [ Validators.min(123) ]
})
It will work. But I don't like it. I strongly prefer to have one data structure for myForm, all APIs and data stores. Doing this.myForm.setValue(dataFromApi) or the opposite .getValue() variant is really helpful.