I'm currently working with the latest version of Angular and I'm attempting to implement a custom validation for checking a code through a RestAPI. The example below is functional, but it doesn't trigger on keypress events; it only activates onblur. The text "Code not available" only appears when the input field loses focus. Any suggestions?
Thank you in advance for your assistance!
This is the formbuilder
this.form = this.formBuilder.group({
code: ['',
[Validators.required, Validators.pattern('^[A-Za-z0-9]{4}')],
this.asyncCodeValidator.validate(),
]
});
This is the asyncCodeValidator service
@Injectable({ providedIn: 'root' })
export class AsyncCodeValidatorService {
constructor(private codeService: CampaignService) {}
validate(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return this.searchCode(control.value).pipe(
map(result => {
return result.available ? null : { notUnique: 'Action code not unique' };
})
);
};
}
searcCode(code: string): Observable<CodeValidate> {
return timer(500).pipe(
switchMap(() => {
return this.codeService.validateCode(code); // return Observable<CodeValidate>
})
);
}
}
This is the html control
<form [formGroup]="form">
<input type="text" formControlName="code">
<p style="color: red" *ngIf="form.get('code').errors?.notUnique">code not available</p>
</form>
Using
"@angular/common": "11.2.12",
"@angular/compiler": "11.2.12",
"@angular/core": "11.2.12",
"@angular/forms": "11.2.12",
"@angular/material": "11.2.12",