- 创建自定义同步表单验证器步骤:
- 定义验证函数:该函数接收一个
AbstractControl
类型的参数,返回一个ValidationErrors | null
类型的值。如果验证失败,返回一个包含错误信息的对象;如果验证成功,返回null
。
- 注册验证器:在表单控件定义时,将自定义验证函数注册到控件的
validators
数组中。
- 示例:验证输入是否为正整数:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function positiveIntegerValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) {
return null;
}
const valid = /^[1-9]\d*$/.test(value);
return valid? null : { positiveInteger: true };
};
}
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { positiveIntegerValidator } from './positive - integer.validator';
@Component({
selector: 'app - my - form',
templateUrl: './my - form.component.html'
})
export class MyFormComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
numberInput: new FormControl('', [Validators.required, positiveIntegerValidator()])
});
}
}
<form [formGroup]="myForm">
<input type="text" formControlName="numberInput">
<div *ngIf="myForm.get('numberInput').hasError('required') && (myForm.get('numberInput').touched || myForm.get('numberInput').dirty)">
此字段为必填项
</div>
<div *ngIf="myForm.get('numberInput').hasError('positiveInteger') && (myForm.get('numberInput').touched || myForm.get('numberInput').dirty)">
请输入正整数
</div>
</form>