Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

I've just used Validators.compose:

this.form = this.fb.group({
  field: ['', Validators.compose([Validators.required, this.validateCardNumber])],
  ...
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!