Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minLength and maxLength validators not working in Angular7 Reactive Form

I am trying to use Validators.minLength and Validators.maxLength in Angular7 using a Reactive Form but get the following error:

ERROR Error: Expected validator to return Promise or Observable.

This is the typescript code I have:

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)]

 })
}

And this is my template 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>

Can you see what the problem is?

like image 766
Rich Avatar asked Dec 13 '22 12:12

Rich


1 Answers

When you are applying multiple validators, It should be an array:

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

 })
}
like image 85
nircraft Avatar answered May 12 '23 00:05

nircraft