Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Straightforward custom validation in angular2

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?

like image 894
Jordi Avatar asked Dec 04 '22 22:12

Jordi


2 Answers

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

like image 196
Ján Halaša Avatar answered Dec 09 '22 15:12

Ján Halaša


I've just used Validators.compose:

this.form = this.fb.group({
  field: ['', Validators.compose([Validators.required, this.validateCardNumber])],
  ...
}
like image 37
Jordi Avatar answered Dec 09 '22 15:12

Jordi