asynchronous validators reactive forms

27 views Asked by At


payerGeneralInformationValidators = this.formBuilder.group({
        'payerName': ['', [Validators.required, Validators.pattern('[a-zA-Z 0-9`~!@#$%^&,.\'\"*()_+-]*$'), Validators.maxLength(256), this.createValidator()]],
        'aliasName': ['', []],
        'address1': ['', []],
        'address2': ['', []],
        'city': ['', [Validators.pattern('[a-zA-Z 0-9`~!@#$%^&,.\'\"*()_+-]*$')]],
        'state': ['', []],
        'zip': ['', [Validators.pattern(/^\d{5}(-\d{4})?$/)]],
    });

createValidator(): AsyncValidatorFn {
        return (control: AbstractControl): Observable<ValidationErrors> => {
          return of(true)
            .pipe(
              map((result: boolean) =>
                result ? null : { isOutsideState: true }
              )
            );
        };
      }

I place (true) as a mock observable, to make easier the test

I'm trying to validate payerName, but CreateValidtor() function never returns null or { isOutsideState: true }

1

There are 1 answers

0
letmejustfixthat On

You need to inform the observer, I think it should work like this:

createValidator: AsyncValidatorFn = control => {
    return new Observable<ValidationErrors | null>(observer => {
        const result = control.value;
        observer.next(result ? null : {isOutsideState: true});
        observer.complete();
    });
}