Simple user check in angular2

I created this check function:

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

So, in my reactive form:

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

When I write any character in this field, I get this error:

Error: The expected validator to return a promise or observation.

Any ideas?

+4
source share
2 answers

I just used Validators.compose:

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

The third element in the field array is the asynchronous validator (or an array of them). Therefore, 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(...)

API- FormBuilder API , FormGroup FormControl-s, FormControl: https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

+11

Source: https://habr.com/ru/post/1673953/


All Articles