Angular

Last Updated: 8/31/2023

Async Validators

Async Operations

  • There are times we call the server to validate the given value. eg to check username is taken or not
  • Synchronous means when we call the server there is going to be a delay based on the connection speed. The process that is executing our code blocks while waiting for the result from the server. If the process blocks the user can't interact with the browser
  • Asynchronous Operation means process calls the server behind the scenes and when result arrives it displays it to the user
  • Asynchronous means non blocking. eg Operations - Calling the server (AJAX), timer functions

Custom Async Validator

  • Use AsyncValidatorFn for validator that involves asynchronous operation
  • FormControl - third parameter - AsyncValidatorFn or array of AsyncValidatorFn
  • In Javascript we use Promises or Observables to work with asynchronous operations
  • In promises
    • resolve - return value to the consumer of promise
    • reject - in case of failure return failure message
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
 	return new Promise((resolve, reject) => {
 		setTimeout(() => {
 			if((control.value as string) == "mosh")
 				resolve({shouldBeUnique: true}})
 			else 
 				resolve(null)
 		}, 2000)
	})
}
username:  new FormControl(
	'', 
	[Validators.required, Validators.minLength(3), UsernameValidators.cannotContainWhiteSpace], 
	UsernameValidators.shouldBeUnique
),	
<div *ngIf="username.errors.shouldBeUnique">Username is already taken</div>