如何在angular2中验证FormArray长度

时间:2017-02-12 06:20:21

标签: angular angular2-forms

我在angular2中有一个数据驱动表单,如下所示

Array

我想在this.formBuilder.group({ 'name': ['',Validators.required], 'description': ['', Validators.required], 'places': this.formBuilder.array([], Validators.minlength(1)) }) formArray中添加验证,所以我要添加place验证,但是minlength验证不适用于formArray。

formArray的其他验证是什么,因此只有当places数组包含至少一个地方时,表单才有效。

7 个答案:

答案 0 :(得分:22)

Validators.required为你带来了魔力:

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>

答案 1 :(得分:20)

将此自定义验证程序添加到验证服务中:

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

        return { 'minLengthArray': {valid: false }};
    }
}

然后在创建表单时执行以下操作:

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

您可以通过查看FormArray

来检查FormArray.hasError('minLengthArray')的错误

答案 2 :(得分:6)

因为您使用了错误的验证程序功能名称:minlength - &gt; minLength

演示代码:

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

答案 3 :(得分:3)

如果您尝试向formarray添加验证,请尝试这可以帮助您,

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

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

initPlaces将根据需要返回formGroup并进行验证。

答案 4 :(得分:1)

好的明确方法是:

创建一个Array.validator.ts并将所有自定义验证放在此处,例如minLengthmaxLength

import { ValidatorFn, AbstractControl, FormArray } from '@angular/forms';

// Array Validators
export class ArrayValidators {

    // max length
    public static maxLength(max: number): ValidatorFn | any {
        return (control: AbstractControl[]) => {
            if (!(control instanceof FormArray)) return;
            return control.length > max ? { maxLength: true } : null;
        }
    }

    // min length
    public static minLength(min: number): ValidatorFn | any {
        return (control: AbstractControl[]) => {
            if (!(control instanceof FormArray)) return;
            return control.length < min ? { minLength: true } : null;
        }
    }
}

然后只需导入该文件并在需要的地方使用验证即可:

import { ArrayValidators } from './array.validator'; // Import it

'hobbies':new FormArray([],ArrayValidators.minLength(2)) // Use it

WORKING DEMO


  

注意:

     

您也可以直接使用此软件包 ng-validator (参考是从此软件包中获得的),但是如果   您只需要进行数组验证即可,就像上面一样。

答案 5 :(得分:0)

具有模板

<div formArrayName="items">
    <div *ngFor="[...] let i = index" [formGroupName]="i">

    [...]

    </div>
</div>

您可以简单地在按钮中使用它:

[disabled]="!myForm.get('items.1')"

答案 6 :(得分:0)

faces-config.xml

只需使用 <renderer> <component-family>org.primefaces.component</component-family> <renderer-type>org.primefaces.component.WizardRenderer</renderer-type> <renderer-class>myImportantPackage.WizardRenderer</renderer-class> </renderer> https://angular.io/api/forms/Validators#minLength