从 Angular 2 FormGroup 获取所有验证错误

根据这个代码:

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

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

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

185306 次浏览

可以迭代 this. form.error 属性。

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

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应更改为表单实例名称。

它的工作原理是这样的: 我们从格式为 {[p: string]: AbstractControl}的表单中获取所有控件,并循环访问每个错误键,以获取错误的详细信息。它跳过 null错误值。

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

export class GenericValidator {
constructor(private validationMessages: { [key: string]: { [key: string]: string } }) {
}


processMessages(container: FormGroup): { [key: string]: string } {
const messages = {};
for (const controlKey in container.controls) {
if (container.controls.hasOwnProperty(controlKey)) {
const c = container.controls[controlKey];
if (c instanceof FormGroup) {
const childMessages = this.processMessages(c);
// handling formGroup errors messages
const formGroupErrors = {};
if (this.validationMessages[controlKey]) {
formGroupErrors[controlKey] = '';
if (c.errors) {
Object.keys(c.errors).map((messageKey) => {
if (this.validationMessages[controlKey][messageKey]) {
formGroupErrors[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
}
})
}
}
Object.assign(messages, childMessages, formGroupErrors);
} else {
// handling control fields errors messages
if (this.validationMessages[controlKey]) {
messages[controlKey] = '';
if ((c.dirty || c.touched) && c.errors) {
Object.keys(c.errors).map((messageKey) => {
if (this.validationMessages[controlKey][messageKey]) {
messages[controlKey] += this.validationMessages[controlKey][messageKey] + ' ';
}
})
}
}
}
}
}
return messages;
}
}

我把它从 黛博拉克和修改了一点点。

这是解决方案与 FormGroup内支持(像这里一样)

测试地点: 角度4.3.6

获得表单验证错误

import { AbstractControl, FormGroup, ValidationErrors } from '@angular/forms';


export interface AllValidationErrors {
control_name: string;
error_name: string;
error_value: any;
}


export interface FormGroupControls {
[key: string]: AbstractControl;
}


export function getFormValidationErrors(controls: FormGroupControls): AllValidationErrors[] {
let errors: AllValidationErrors[] = [];
Object.keys(controls).forEach(key => {
const control = controls[ key ];
if (control instanceof FormGroup) {
errors = errors.concat(getFormValidationErrors(control.controls));
}
const controlErrors: ValidationErrors = controls[ key ].errors;
if (controlErrors !== null) {
Object.keys(controlErrors).forEach(keyError => {
errors.push({
control_name: key,
error_name: keyError,
error_value: controlErrors[ keyError ]
});
});
}
});
return errors;
}

使用示例 :

if (!this.formValid()) {
const error: AllValidationErrors = getFormValidationErrors(this.regForm.controls).shift();
if (error) {
let text;
switch (error.error_name) {
case 'required': text = `${error.control_name} is required!`; break;
case 'pattern': text = `${error.control_name} has wrong pattern!`; break;
case 'email': text = `${error.control_name} has wrong email format!`; break;
case 'minlength': text = `${error.control_name} has wrong length! Required length: ${error.error_value.requiredLength}`; break;
case 'areEqual': text = `${error.control_name} must be equal!`; break;
default: text = `${error.control_name}: ${error.error_name}: ${error.error_value}`;
}
this.error = text;
}
return;
}

或者您可以使用这个库来获取所有错误,即使是来自深度和动态表单的错误。

npm i @naologic/forms

如果您想在自己的窗体上使用静态函数

import {NaoFormStatic} from '@naologic/forms';
...
const errorsFlat = NaoFormStatic.getAllErrorsFlat(fg);
console.log(errorsFlat);

如果您想使用 NaoFromGroup,您可以导入并使用它

import {NaoFormGroup, NaoFormControl, NaoValidators} from '@naologic/forms';
...
this.naoFormGroup = new NaoFormGroup({
firstName: new NaoFormControl('John'),
lastName: new NaoFormControl('Doe'),
ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
});


const getFormErrors = this.naoFormGroup.getAllErrors();
console.log(getFormErrors);
// --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}

读读 完整的文件

// IF not populated correctly - you could get aggregated FormGroup errors object
let getErrors = (formGroup: FormGroup, errors: any = {}) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
errors[field] = control.errors;
} else if (control instanceof FormGroup) {
errors[field] = this.getErrors(control);
}
});
return errors;
}


// Calling it:
let formErrors = getErrors(this.form);

我使用的是角度5,您可以简单地使用 FormGroup 检查表单的状态属性。

this.form = new FormGroup({
firstName: new FormControl('', [Validators.required, validateName]),
lastName: new FormControl('', [Validators.required, validateName]),
email: new FormControl('', [Validators.required, validateEmail]),
dob: new FormControl('', [Validators.required, validateDate])
});

Status 将是“ INVALID”,除非所有字段都通过所有验证规则。

最棒的是它能实时检测到变化。

尝试此操作,它将调用表单中所有控件的验证:

validateAllFormControl(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormControl(control);
}
});
}

对于大型 FormGroup 树,您可以使用 loash 清理该树,并获得仅包含有错误的控件的树。这是通过重复使用子控件(例如使用 allErrors(formGroup))来完成的,并删除任何完全有效的子控件组:

private isFormGroup(control: AbstractControl): control is FormGroup {
return !!(<FormGroup>control).controls;
}


// Returns a tree of any errors in control and children of control
allErrors(control: AbstractControl): any {
if (this.isFormGroup(control)) {
const childErrors = _.mapValues(control.controls, (childControl) => {
return this.allErrors(childControl);
});


const pruned = _.omitBy(childErrors, _.isEmpty);
return _.isEmpty(pruned) ? null : pruned;
} else {
return control.errors;
}
}

这是另一个递归收集错误的变体,它不依赖于任何外部库,比如 lodash(仅仅是 ES6) :

function isFormGroup(control: AbstractControl): control is FormGroup {
return !!(<FormGroup>control).controls;
}


function collectErrors(control: AbstractControl): any | null {
if (isFormGroup(control)) {
return Object.entries(control.controls)
.reduce(
(acc, [key, childControl]) => {
const childErrors = collectErrors(childControl);
if (childErrors) {
acc = {...acc, [key]: childErrors};
}
return acc;
},
null
);
} else {
return control.errors;
}
}

基于 @ MixerOID响应,下面是我作为组件的最终解决方案(也许我创建了一个库)。我也支持 FormArray 的:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';


interface AllValidationErrors {
controlName: string;
errorName: string;
errorValue: any;
}


@Component({
selector: 'app-form-errors',
templateUrl: './form-errors.component.html',
styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {


@Input() form: FormGroup;
@Input() formRef: ElementRef;
@Input() messages: Array<any>;


private errors: AllValidationErrors[];


constructor(
private translateService: TranslateService
) {
this.errors = [];
this.messages = [];
}


ngOnInit() {
this.form.valueChanges.subscribe(() => {
this.errors = [];
this.calculateErrors(this.form);
});


this.calculateErrors(this.form);
}


calculateErrors(form: FormGroup | FormArray) {
Object.keys(form.controls).forEach(field => {
const control = form.get(field);
if (control instanceof FormGroup || control instanceof FormArray) {
this.errors = this.errors.concat(this.calculateErrors(control));
return;
}


const controlErrors: ValidationErrors = control.errors;
if (controlErrors !== null) {
Object.keys(controlErrors).forEach(keyError => {
this.errors.push({
controlName: field,
errorName: keyError,
errorValue: controlErrors[keyError]
});
});
}
});


// This removes duplicates
this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
return t.controlName === error.controlName && t.errorName === error.errorName;
}) === index);
return this.errors;
}


getErrorMessage(error) {
switch (error.errorName) {
case 'required':
return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
default:
return 'unknown error ' + error.errorName;
}
}
}

还有 HTML:

<div *ngIf="formRef.submitted">
<div *ngFor="let error of errors" class="text-danger">
\{\{getErrorMessage(error)}}
</div>
</div>

用法:

<app-form-errors [form]="languageForm"
[formRef]="formRef"
[messages]="{language: 'Language'}">
</app-form-errors>

递归方法从角度形式 中检索所有错误,在创建了任何类型的公式结构之后,都没有办法从形式中检索所有错误。这对于调试目的非常有用,但对于绘制那些错误也非常有用。

测试角度9

getFormErrors(form: AbstractControl) {
if (form instanceof FormControl) {
// Return FormControl errors or null
return form.errors ?? null;
}
if (form instanceof FormGroup) {
const groupErrors = form.errors;
// Form group can contain errors itself, in that case add'em
const formErrors = groupErrors ? {groupErrors} : {};
Object.keys(form.controls).forEach(key => {
// Recursive call of the FormGroup fields
const error = this.getFormErrors(form.get(key));
if (error !== null) {
// Only add error if not null
formErrors[key] = error;
}
});
// Return FormGroup errors or null
return Object.keys(formErrors).length > 0 ? formErrors : null;
}
}

对于它可能关心的人——我调整了 Andreas 代码,以便在一个平面对象中获得所有错误代码,从而更容易地记录可能出现的错误。

请考虑:

export function collectErrors(control: AbstractControl): any | null {
let errors = {};
let recursiveFunc = (control: AbstractControl) => {
if (isFormGroup(control)) {
return Object.entries(control.controls).reduce(
(acc, [key, childControl]) => {
const childErrors = recursiveFunc(childControl);
if (childErrors) {
if (!isFormGroup(childControl)) {
errors = { ...errors, [key]: childErrors };
}
acc = { ...acc, [key]: childErrors };
}
return acc;
},
null
);
} else {
return control.errors;
}
};
recursiveFunc(control);
return errors;
}
**I met the same problem and for finding all validation errors and
displaying only first error, I wrote next method:**


> first declare variable on top
public errors: any = [];
public fieldError: any = '';


> now subscribe form on noOnInit
  

this.form.valueChanges.subscribe(() => {
this.showOnlyFirstError(this.form);
this.errors = []
});
this.showOnlyFirstError(this.form);


> now call function


showOnlyFirstError(form) {
Object.keys(form.controls).forEach(key => {


const controlErrors: ValidationErrors = form.get(key).errors;
if (controlErrors != null) {
Object.keys(controlErrors).forEach(keyError => {
const showMessage = key + " is " + keyError
this.errors.push(showMessage)
this.fieldError = this.errors[0]
});
}
});
}

我需要显示非常复杂的 FormGroup 控件的所有错误,这些控件包含 FormControls、 FromGroup 和 FormArray

我试图找到简单的解决方案,但我无法找到完美的解决方案,支持所有类型的控件,所以我开发了以下简单的递归函数,我与所有人分享:

export interface FieldError {
formGroupName: string;
fieldName: string;
errorCode: string;
}


export function getFormErrors(
control: AbstractControl,
formGroupName: string,
fieldName: string,
errors: FieldError[]) {


if (control instanceof FormGroup) {
Object.keys(control.controls).forEach(controlName => {
let formControl = control.get(controlName);
if (formControl) {
let fGroupName = formGroupName + "-" + controlName;
getFormErrors(formControl, fGroupName, controlName, errors);
}
})
}


if (control instanceof FormArray) {
control.controls.forEach((fControl: AbstractControl, index) => {
let fGroupName = formGroupName + "-" + index;
getFormErrors(fControl, fGroupName, "Array", errors);
})
}


if (control instanceof FormControl) {
const controlErrors: ValidationErrors | null = control.errors;
if (controlErrors) {
Object.keys(controlErrors).forEach(errorCode => {
errors.push({
formGroupName: formGroupName,
fieldName: fieldName,
errorCode: errorCode
})
});
}
}
}

用法如下:

    let errors: FieldError[] = []
getFormErrors(YOUR_FORM_GROUP, "root", "", errors);

调整 公认的答案以返回一个字符串,然后将其打印到控制台:

function getFormValidationErrors(form: FormGroup): string {
return Object.keys(form.controls)
.map((control) => {
const controlErrors = form.get(control).errors;
if (!controlErrors) {
return [];
}
const controlErrorsString = Object.keys(controlErrors)
.flatMap(
(keyError) => `${keyError}: ${controlErrors[keyError]}`
)
.join(', ');
return `${control}: {${controlErrorsString}}`;
})
.filter((list) => list.length > 0)
.join('\n');
}