BobC
BobC

Reputation: 349

Angular 5 FormGroup Validator Expected validator to return Promise or Observable

My FormGroup validator raises the "Promise or Observable" error. I've studied many SO examples explaining to return an Observable or Promise as the error states, but none explain why a return of null works fine in the web service calling block, but not at the end of the validator function, if it drops through to the bottom.

The validator is working fine. It's just that I'd like to eliminate the error when getting started.

component.ts

    ngOnInit() {
    this.dnFormGroup = this.formBuilder.group({
    displayName: ['', [Validators.required], this.validateDisplayName.bind(this)] //NOTE: 2nd option is required! See https://angular.io/api/forms/FormGroup#description
    }); 
}

public validateDisplayName(control: AbstractControl) {
    if(control.value.length >= 3 && control.value !== this.authService.displayName) {
        this.displayName = control.value;

        return this.authService.validateDisplayName(control.value).then( 
           (res) => {
            if(res) {
              //displayName already used
              return { displayNameTaken: true };              
            } else {
              //displayName can be used
              return null;
            }
          },
          (err) => {
            return { displayNameTaken: true };                            
       });      
    }
    return null;  //<<<<< ERROR "Expected validator to return Promise or Observable"
}

Thanks, Bob

Upvotes: 1

Views: 4801

Answers (1)

Loheek
Loheek

Reputation: 1985

Don't know much about validators, but only the type of the first return in your function will matter.

In the if block, you return a Promise (that returns either null or an object but it's not important) so it's OK.

But outside the block, you just return null, that is neither a Promise nor an object. Try to make it a Promise that returns null (with return Promise.resolve(null)) or an Observable that returns null (with import { of } from 'rxjs'; and return of(null)).

Upvotes: 2

Related Questions