我推荐另一种方法来处理反应式表单中的验证错误。
查看stackblitz 上的工作示例。
这是一个例子:
第 1 步:创建类 ErrorMessage
这个类是 ErrorMessage 的模型,您将在表单模板中使用它。
export class ErrorMessage {
constructor(
public forControl: string,
public forValidator: string,
public text: string
) { }
}
第 2 步:创建您的 FormGroup
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.createForm();
}
createForm() {
this.myForm = this.fb.group({
name: [null, [Validators.required, Validators.maxLength(255)]],
email: [null, [Validators.required, Validators.email, Validators.maxLength(255)]],
password: [null, [Validators.required, Validators.minLength(12)]]
});
}
第 3 步:为您的表单创建带有错误消息的 const
为每个表单字段验证器创建一条错误消息。这是一个包含三个字段的表单示例:姓名、电子邮件、密码。
import { ErrorMessage } from './error-message';
export const MyFormErrorMessage = [
new ErrorMessage('name', 'required', 'Name is required'),
new ErrorMessage('name', 'maxlength', 'Name should have maximal 255 chars'),
new ErrorMessage('email', 'required', 'Email is required'),
new ErrorMessage('email', 'email', 'Email is not valid'),
new ErrorMessage('email', 'maxlength', 'Email should have maximal 255 chars'),
new ErrorMessage('password', 'required', 'Password is required'),
new ErrorMessage('password', 'minlength', 'Password should have minimal 12 chars')
];
第 4 步:在您的 component.ts 中为 errors 创建变量
myForm: FormGroup;
errors: { [key: string]: string } = {};
constructor(private fb: FormBuilder) { }
第 5 步:通过表单状态更改进行错误处理的功能
在此函数中,您迭代MyFormErrorMessage 并获得对每个表单字段的控制权。然后检查控制是否有效,并将错误消息添加到errors变量。
updateErrorMessages() {
this.errors = {};
for (const message of MyFormErrorMessage) {
const control = this.myForm.get(message.forControl);
if (control &&
control.dirty &&
control.invalid &&
control.errors[message.forValidator] &&
!this.errors[message.forControl]) {
this.errors[message.forControl] = message.text;
}
}
}
第 6 步:订阅 myForm statusChanges 并运行 updateErrorMessages 函数
添加这个:
this.myForm.statusChanges.subscribe(() => this.updateErrorMessages());
致createForm():
createForm() {
this.myForm = this.fb.group({
name: [null, [Validators.required, Validators.maxLength(255)]],
email: [null, [Validators.required, Validators.email, Validators.maxLength(255)]],
password: [null, [Validators.required, Validators.minLength(12)]]
});
this.myForm.statusChanges.subscribe(() => this.updateErrorMessages());
}
第 7 步:修改表单模板
现在您可以在模板中使用errors vairable 来输出错误消息:
<form [formGroup]="myForm" (onSubmit)="submitForm()">
<div class="form-group"
[class.has-error]="errors.name"
[class.has-success]="!errors.name && myForm.controls['name'].value">
<label for="name">Name</label>
<input type="text" id="name" formControlName="name" required>
<span class="help-text" *ngIf="errors.name">{{ errors.name }}</span>
</div>
<div class="form-group"
[class.has-error]="errors.email"
[class.has-success]="!errors.email && myForm.controls['email'].value">
<label for="email">Email</label>
<input type="text" id="email" formControlName="email" required>
<span class="help-text" *ngIf="errors.email">{{ errors.email }}</span>
</div>
<div class="form-group"
[class.has-error]="errors.password"
[class.has-success]="!errors.password && myForm.controls['password'].value">
<label for="password">Password</label>
<input type="password" id="password" formControlName="password" required>
<span class="help-text" *ngIf="errors.password">{{ errors.password }}</span>
</div>
</form>
在我的项目中,我使用这种方式来处理来自验证器的错误。这种方式也适用于自定义验证器。
此解决方案的优点: