FormGroup获取所有验证错误

FormGroup获取所有验证错误

本文介绍了从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?

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

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 next 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 yours.

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

It works in next way: we get all our controls from form in format {[p: string]: AbstractControl} and iterate by each error key, for 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获取所有验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:46