如何在angular2中验证FormArray长度

Cha*_*har 20 angular2-forms angular

我有一个像angular2一样的数据驱动形式,如下所示

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

我想为placeformArray 添加验证,所以我添加minlength验证,但minlength验证不适用于formArray.

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

小智 26

Validators.required 给你带来的魔力:

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

  • 你好,我实现了这个,但它不起作用。即使我勾选了一个复选框,我也无法将 form.valid 更改为“true”。还有什么我需要补充的吗? (2认同)
  • 这是正确的答案,“Validators.required”调用名为“isEmptyInputValue”的函数,该函数检查值是否为“null”或“length === 0”。请参阅[Angular源文件](https://github.com/angular/angular/blob/d1ea1f4c7f3358b730b0d94e65b00bc28cae279c/packages/forms/src/validators.ts#L199) (2认同)

use*_*362 22

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

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

        return { 'minLengthArray': {valid: false }};
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

您可以FormArray通过检查来检查错误FormArray.hasError('minLengthArray')

  • 嘿,它实际上有效:)-但是如何使它“冒泡”到表单中-防止提交(对我而言不行)? (2认同)

Tie*_*han 7

因为您使用了错误的验证器函数名称:minlength- >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);
  }

}
Run Code Online (Sandbox Code Playgroud)

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


Par*_*ain 5

如果您尝试向 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)]]           
        });
  }
Run Code Online (Sandbox Code Playgroud)

initPlaces将根据要求简单地返回带有验证的 formGroup 。


Viv*_*shi 5

做到这一点的好方法是:

创建一个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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

'hobbies':new FormArray([],ArrayValidators.minLength(2)) // Use it
Run Code Online (Sandbox Code Playgroud)

工作演示


注意 :

您也可以直接使用此程序包ng-validator(此程序包中的参考),但是如果您只需要进行数组验证,则可以像上面一样进行操作。