- 在组件中定义自定义表单级验证器,并在控件初始化时将其添加到FormGroup中。
import { Component } from '@angular/core';
import { FormControl, FormGroup, ValidatorFn, AbstractControl } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
`
})
export class AppComponent {
formGroup: FormGroup;
constructor() {
const nameValidator: ValidatorFn = (control: AbstractControl): {[key: string]: any} | null => {
const value = control.value;
const invalid = value && value.length < 5;
return invalid ? {'nameInvalid': {value}} : null;
};
this.formGroup = new FormGroup({
name: new FormControl('', { validators: nameValidator, updateOn: 'blur' })
});
}
}
- 在模板中绑定控件的错误提示信息。
Name must be at least 5 characters long