How to Validate FormArray length in angular2

匿名 (未验证) 提交于 2019-12-03 02:51:02

问题:

I have a data driven form in angular2 like below

this.formBuilder.group({   'name': ['',Validators.required],   'description': ['', Validators.required],   'places': this.formBuilder.array([], Validators.minlength(1))  }) 

I want to add validations to the place formArray, so i am adding minlength validation, but minlength validation is not working on formArray.

What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.

回答1:

Add this custom validator to your validation service:

minLengthArray(min: number) {     return (c: AbstractControl): {[key: string]: any} => {         if (c.value.length >= min)             return null;          return { 'minLengthArray': {valid: false }};     } } 

And then when creating the form do the following:

this.formBuilder.group({   'name': ['',Validators.required],   'description': ['', Validators.required],   'places': this.formBuilder.array([], this.validationService.minLengthArray(1))  }); 

And you can check errors against the FormArray by checking FormArray.hasError('minLengthArray')



回答2:

Validators.required does the magic for you:

this.formGroup = this.formBuilder.group({     taskTreeId: [Common.UID()],     executionProgrammedTime: ["", [Validators.required]],     description: [""],     tasks: this.formBuilder.array([], Validators.required) }); 
<button type="button" class="btn btn-success btn-rounded"      [disabled]="!formGroup.valid">SAVE</button> 


回答3:

because you using wrong validator function name: minlength -> minLength

demo code:

import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';  @Component({   selector: 'app-root',   template: `     <form novalidate [formGroup]="tpForm" (ngSubmit)="onSubmit()">       <div><input type="text" formControlName="name"></div>       <div><textarea formControlName="description"></textarea></div>       <div formArrayName="places">         <button type="button" (click)="addPlace()">+</button>         <div *ngFor="let place of places.controls; let i = index">           <div>               <span>Places {{i + 1}}</span>               <button type="button" *ngIf="places.controls.length > 0"                    (click)="removePlace(i)">                   x               </button>           </div>           <input type="text" [formControlName]="i">         </div>       </div>       <button type="submit">Submit</button>     </form>      <p>Status: {{ tpForm.valid }}</p>   `,   styles: [     `       `   ] }) export class AppComponent implements OnInit {   tpForm: FormGroup;    constructor(private fb: FormBuilder) {}    ngOnInit() {     this.tpForm = this.fb.group({       'name': ['',Validators.required],       'description': ['', Validators.required],       'places': this.fb.array([         this.fb.control('')       ], Validators.minLength(1))     })   }    get places(): FormArray {     return this.tpForm.get('places') as FormArray;   }    onSubmit() {    }    addPlace() {     this.places.push(this.fb.control(''));   }    removePlace(index) {     this.places.removeAt(index);   }  } 

Plunker: https://plnkr.co/edit/cfi7nN?p=preview



回答4:

if you are trying to add validation to formarray try this may help you,

this.formBuilder.group({   'name': ['',Validators.required],   'description': ['', Validators.required],   'places': this.formBuilder.array(this.initPlaces())  })  initPlaces() {                return this._fb.group({             places: ['',[Validators.minLength(1)]]                    });   } 

this initPlaces will simply return formGroup with validation as per requirement.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!