Skip to content

Instantly share code, notes, and snippets.

@BrianJVarley
Created July 4, 2020 19:45
Show Gist options
  • Save BrianJVarley/6238f76c57abebf4418474c842e3b101 to your computer and use it in GitHub Desktop.
Save BrianJVarley/6238f76c57abebf4418474c842e3b101 to your computer and use it in GitHub Desktop.
Cross Control Validation Angular Forms
let input1$ = this.form.controls.input1.valueChanges;
let input2$ = this.form.controls.input2.valueChanges;
let input3$ = this.form.controls.input3.valueChanges;
combineLatest(input1$, input2$, input3$)
.do(([input1, input2, input3]) => {
this.form.controls.input1.clearAsyncValidators();
})
.debounceTime(500)
.subscribe(([input1, input2, input3]) => {
if (!input1 || !input2 || !input3) return null;
let request = {
input1,
input2,
input3
}
const inputValidatorFn = this.getEftValidator(request);
this.form.controls.input1.setAsyncValidators(inputValidatorFn);
this.form.controls.input1.updateValueAndValidity();
});
private getEftValidator(request): ValidatorFunction {
return ( control: FormGroup ) => {
return new Promise((resolve, reject) => {
this.someService.validateEft(request)
.subscribe((serviceResponse)=>{
let response = serviceResponse.json();
if( response && response.data.valid ) return resolve(null);
if( response && !response.data.valid ) {
if( response.data.reason === 'reason1' )resolve({reason1: 'more info about error'})
if( response.data.reason === 'reason2') resolve({reason2: 'more info about error'})
}
})
.catch(err=>handleError(err));
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment