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)
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')
因为您使用了错误的验证器函数名称: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
如果您尝试向 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 。
做到这一点的好方法是:
创建一个Array.validator.ts并将所有自定义验证放在那边,例如minLength,maxLength等等
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(此程序包中的参考),但是如果您只需要进行数组验证,则可以像上面一样进行操作。
| 归档时间: |
|
| 查看次数: |
30193 次 |
| 最近记录: |