从 Angular 2 FormGroup 获取所有验证错误 [英] Get all validation errors from Angular 2 FormGroup

查看:41
本文介绍了从 Angular 2 FormGroup 获取所有验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

this.form = this.formBuilder.group({
  email: ['', [Validators.required, EmailValidator.isValid]],
  hasAcceptedTerms: [false, Validators.pattern('true')]
});

如何从 this.form 获取所有验证错误?

How can I get all validation errors from this.form?

我正在编写单元测试并希望在断言消息中包含实际的验证错误.

I'm writing unit tests and want to include the actual validation errors in the assert message.

推荐答案

我遇到了同样的问题,为了找到所有验证错误并显示它们,我写了这个方法:

I met the same problem and for finding all validation errors and displaying them, I wrote this method:

getFormValidationErrors() {
  Object.keys(this.productForm.controls).forEach(key => {
    const controlErrors: ValidationErrors = this.productForm.get(key).errors;
    if (controlErrors != null) {
      Object.keys(controlErrors).forEach(keyError => {
       console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
      });
    }
  });
}

表单名称 productForm 应更改为您的表单实例名称.

Form name productForm should be changed to your form instance name.

它是这样工作的:我们以 {[p: string]: AbstractControl} 格式从表单中获取所有控件,并通过每个错误键进行迭代,以获取错误的详细信息.它跳过 null 错误值.

It works in this way: we get all our controls from the form in format {[p: string]: AbstractControl} and iterate by each error key, to get details of error. It skips null error values.

它也可以更改为在模板视图上显示验证错误,只需将 console.log(..) 替换为您需要的即可.

It also can be changed for displaying validation errors on the template view, just replace console.log(..) to what you need.

这篇关于从 Angular 2 FormGroup 获取所有验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆