Home > Mobile >  Trying to create an async validator using pipe/map
Trying to create an async validator using pipe/map

Time:01-24

The ideia is simple. I have an input where the user enters a string. I would like to be able to validate it. I managed to do it with SetTimeout and a simple if/else logic but I would like to understand how pipe/map can help work in this case.

this is what I came up with so far, but instead of having only test2 be invalid, I'm getting my name always as invalid. I'm probably getting the logic wrong somewhere

 asyncInvalidProjectName(control: FormControl): Promise<any> | Observable<any> {
    return of(control.value).pipe(
      map(value => value === 'test2' ? { 'invalidProjectName': true } : null),
      delay(500)
    );
  }

CodePudding user response:

Async validators are a separate category from validators. If you're using FormBuilder, then it's, for example,

this.form = this.formBuilder.group({
    foo: ['initial value', null, this.asyncInvalidProjectName],
});

and with FormControl constructor it would be

const control = new FormControl('initial value', {
   asyncValidators: this.asyncInvalidProjectName,
});
  • Related