4

I've created this validation function:

private customValidateField(c: FormControl): any {
    return c.value[0] === 'a' ? null : { notValid: true };
}

So, on my reactive form:

constructor(private fb: FormBuilder)
{
  this.form = this.fb.group({
    field: ['', Validators.required, this.customValidateField],
    ...
  }
}

When I'm writing any character into this field I'm getting this error:

Error: Expected validator to return Promise or Observable.

Any ideas?

2 Answers 2

11

The third item in the "field" array is an asynchronous validator (or an array of them). So to specify multiple synchronous validators, you need to:

Pass them as an array

this.fb.group({
  'formControlName': [this.hero.name, [
      Validators.required,
      Validators.minLength(4)
  ]]
});

or combine them (as Jordi wrote) using

Validators.compose(...)

FormBuilder API doc doesn't discuss the parameters in detail, but since it's just a shortcut for creating FormGroup with FormControl-s, you can take a look at the FormControl constructor: https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

5

I've just used Validators.compose:

this.form = this.fb.group({
  field: ['', Validators.compose([Validators.required, this.validateCardNumber])],
  ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.