Angular 2 FormGroup에서 모든 유효성 검사 오류 가져 오기
이 코드가 주어지면 :
this.form = this.formBuilder.group({
email: ['', [Validators.required, EmailValidator.isValid]],
hasAcceptedTerms: [false, Validators.pattern('true')]
});
모든 유효성 검사 오류를 this.form
어떻게 얻을 수 있습니까?
단위 테스트를 작성 중이며 어설 션 메시지에 실제 유효성 검사 오류를 포함하고 싶습니다.
나는 같은 문제를 만났고 모든 유효성 검사 오류를 찾아서 표시하기 위해 다음 방법을 작성했습니다.
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(..)
. 필요한 항목으로 교체 하기 만하면 됩니다.
이것은 FormGroup
내부 지지대 가있는 솔루션입니다 ( 여기처럼 )
테스트 대상 : Angular 4.3.6
get-form-validation-errors.ts
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 install --save npm i @naologic/forms
당신은 다음을 원할 것입니다
import {SuperForm} from 'npm i @naologic/forms';
그런 다음 FormGroup을 전달하여 모든 오류를 가져옵니다.
const errorsFlat = SuperForm.getAllErrorsFlat(fg);
console.log(errorsFlat);
최신 정보 :
에서 클래식 양식 각도 그룹 대신 사용 npm i @naologic/forms
하고 사용할 수 있습니다 NaoFromGroup
. 몇 가지 새로운 기능이 모든 오류가 보관되어 있습니다.
아직 문서가 없습니다. 코드를보세요.
최신 정보 :
lib에는 AbstractControlOptions를 사용하기 때문에 각도 6이 필요합니다.
이 오류를 재귀 적으로 수집하고 다음과 같은 외부 라이브러리에 의존하지 않는 또 다른 변형입니다 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;
}
}
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;
}
}
Deborahk 에서 가져 오기 약간 수정했습니다.
@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>
시험 시도하면 형식의 모든 컨트롤에 대한 유효성 검사가 호출됩니다.
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);
}
});
}
this.form.errors 속성을 반복 할 수 있습니다.
// 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])
});
this.form.status는 모든 필드가 모든 유효성 검사 규칙을 통과하지 않습니다. "INVALID"가됩니다.
가장 중요한 부분은 실시간으로 변화를 감지한다는 것입니다.
Large FormGroup의 경우 lodash를 사용하여 트리를 정리하고 오류가있는 컨트롤의 트리 만 트리 수 있습니다. 이는 하위 컨트롤 (예 : 사용 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;
}
}
참조 URL : https://stackoverflow.com/questions/40680321/get-all-validation-errors-from-angular-2-formgroup
'ProgramingTip' 카테고리의 다른 글
단어 빈도수 Java 8 (0) | 2021.01.10 |
---|---|
ES6 자바 펼쳐에서 기호 (@)는 무엇을 소유하고 있습니까? (0) | 2021.01.10 |
Google 스프레드 시트에 Lakhs 및 Crores 표시 (0) | 2021.01.09 |
React Native에서 flex 대 flexGrow 대 flexShrink 대 flexBasis? (0) | 2021.01.09 |
사용할 설치 제품은 무엇입니까? (0) | 2021.01.09 |