[Fixed] Expected validator to return Promise or Observable

Issue

I’m trying to do a custom validation on Angular 5 but I’m facing the following error

Expected validator to return Promise or Observable

I just want to return an error to the form if the value doesn’t match the required, here’s my code:

This is the component where my form is

  constructor(fb: FormBuilder, private cadastroService:CadastroService) {
    this.signUp = fb.group({
      "name": ["", Validators.compose([Validators.required, Validators.minLength(2)])],
      "email": ["", Validators.compose([Validators.required, Validators.email])],
      "phone": ["", Validators.compose([Validators.required, Validators.minLength(5)])],
      "cpf": ["", Validators.required, ValidateCpf]
    })     
   }

This code is in the file with the validation I want to implement:

import { AbstractControl } from '@angular/forms';

export function ValidateCpf(control: AbstractControl){
    if (control.value == 13445) {
        return {errorCpf: true}
    }
    return null;
}

Does that type of validation only work with observables or can I do it without being a promise or observable?

Solution

It means that you have to add multiple validators in array

.
Example:

With Error

profileFormGroup = {
  budget: [null, Validators.required, Validators.min(1)]
};

Above one throws error that validator to return Promise or Observable

Fix:

profileFormGroup = {
  budget: [null, [Validators.required, Validators.min(1)]]
};

Explanation:

In angular Reactive form validation done by using in-built validators which could given in array in 2nd postion, when multiple validators used.

FIELD_KEY: [INITIAL_VALUE, [LIST_OF_VALIDATORS]]

Leave a Reply

(*) Required, Your email will not be published