What to return in the angular 2 async validator when using observables

Elisabeth picture Elisabeth · Feb 21, 2017 · Viewed 10.4k times · Source

What do I have to return in the customerNameValidator if the

async validation fails/succeeds that my 'customerName' FormControl is invalid?

this.customerForm = this.formBuilder.group({
customerName: 
[this.newCustomerName, [Validators.minLength(2), Validators.required],[this.customerNameValidator.bind(this)]]
});


customerNameValidator(c: AbstractControl)
{
   return this.service.customerExists(c.value,this.companyId).subscribe(response =>
   {
        if(response == true)
        {
             alert("true");
        }
        else
        {
            alert("false");
        }
   });
}

Answer

Adam picture Adam · Feb 21, 2017

Rather than subscribing, you should map the observable to change the result of the returning stream, rather than reading from it.

customerNameValidator(c: AbstractControl)
{
   return this.service.customerExists(c.value,this.companyId).map(response =>
   {
        if(response == true)
        {
            return { customerExists: true };
        }
        else
        {
            return;
        }
   });
}

Returning an object with a value that is true is how you should return the observable. You may be missing some important steps for async validators though, but because we don't gave all your code it's hard to say. Try checking out this article or this article for more information.