Created
July 4, 2020 19:45
-
-
Save BrianJVarley/6238f76c57abebf4418474c842e3b101 to your computer and use it in GitHub Desktop.
Cross Control Validation Angular Forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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