Angular 6中的表单数组允许你在表单中动态添加或删除表单控件。当你需要在这些动态创建的表单控件中实现自定义验证时,可以通过创建自定义验证器来实现。
自定义验证器是一个函数,它接收一个AbstractControl
对象并返回一个验证结果对象或null
。如果返回一个对象,表示验证失败;如果返回null
,表示验证通过。
自定义验证器可以是同步的或异步的:
Observable
或Promise
。假设我们要在一个动态表单数组中验证每个输入框的值是否为正整数。
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function positiveIntegerValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
if (value === null || value === undefined || value === '') {
return null; // 或者根据需求返回错误信息
}
const isPositiveInteger = /^[1-9]\d*$/.test(value);
return isPositiveInteger ? null : { 'positiveInteger': true };
};
}
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { positiveIntegerValidator } from './positive-integer.validator';
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
})
export class DynamicFormComponent {
dynamicForm: FormGroup;
constructor(private fb: FormBuilder) {
this.dynamicForm = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.dynamicForm.get('items') as FormArray;
}
addItem() {
const itemGroup = this.fb.group({
value: ['', [Validators.required, positiveIntegerValidator()]]
});
this.items.push(itemGroup);
}
onSubmit() {
if (this.dynamicForm.valid) {
console.log(this.dynamicForm.value);
} else {
console.log('Form is invalid');
}
}
}
<form [formGroup]="dynamicForm" (ngSubmit)="onSubmit()">
<div formArrayName="items">
<div *ngFor="let item of items.controls; let i = index" [formGroupName]="i">
<input formControlName="value" placeholder="Enter a positive integer">
<div *ngIf="item.get('value').errors?.positiveInteger">
Value must be a positive integer.
</div>
</div>
</div>
<button type="button" (click)="addItem()">Add Item</button>
<button type="submit">Submit</button>
</form>
问题:自定义验证器没有按预期工作。
原因:
解决方法:
validators
数组中。通过以上步骤,你应该能够在Angular 6的表单数组中成功实现自定义验证。
Elastic 实战工作坊
Elastic 实战工作坊
云+社区沙龙online第6期[开源之道]
Elastic 中国开发者大会
DB TALK 技术分享会
云+社区技术沙龙[第6期]
云+社区开发者大会 长沙站
领取专属 10元无门槛券
手把手带您无忧上云