валидаторы minLength и maxLength не работают в реактивной форме Angular7 - PullRequest
1 голос
/ 25 марта 2019

Я пытаюсь использовать Validators.minLength и Validators.maxLength в Angular7, используя реактивную форму, но получаю следующую ошибку:

Ошибка: ожидаемый валидатор возвращает Promise или Observable.

Это машинописный код, который у меня есть:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from 
  '@angular/forms';

@Component({
    selector: 'app-input-values',
    templateUrl: './input-values.component.html',
    styleUrls: ['./input-values.component.css']
})

export class InputValuesComponent implements OnInit {
   inputValuesForm: FormGroup;

constructor(private fb: FormBuilder) { }

ngOnInit() {
    this.inputValuesForm = this.fb.group({
    interestRate: ['', Validators.required, Validators.minLength(2), 
       Validators.maxLength(5)]

 })
}

И это мой шаблон html:

<form [formGroup]="inputValuesForm" (ngSubmit)="onSubmit()" class="form-horizontal">
  <div class="panel panel-primary">
    <div class="panel-heading">
       <h3 class="panel-title">Input Data</h3>
    </div>

    <div class="panel-body">
      <div class="form-group" [ngClass]="{'has-error': inputValuesForm.get('interestRate').errors &&
     (inputValuesForm.get('interestRate').touched || inputValuesForm.get('interestRate').dirty)}">
        <label class="col-sm-4 control-label" for="interestRate">Interest Rate (omit percent sign):</label>
        <div class="col-sm-2">
          <input id="interestRate" formControlName="interestRate" type="text" class="form-control">
          <span class="help-block" *ngIf="inputValuesForm.get('interestRate').errors &&
        (inputValuesForm.get('interestRate').touched || inputValuesForm.get('interestRate').dirty)">
           <span *ngIf=" inputValuesForm.get('interestRate').errors.required">
             Interest Rate is required
           </span>
           <span
             *ngIf="inputValuesForm.get('interestRate').errors.minlength || inputValuesForm.get('interestRate').errors.maxlength">
              Interest Rate must be greater than 1 character and less than 6 characters
           </span>
         </span>
    </div>
  </div>

    </div>
  </div>
</form>

Вы видите, в чем проблема?

1 Ответ

3 голосов
/ 25 марта 2019

Когда вы применяете несколько валидаторов, это должен быть массив:

ngOnInit() {
    this.inputValuesForm = this.fb.group({
    interestRate: ['', [Validators.required, Validators.minLength(2), 
       Validators.maxLength(5)]]

 })
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...