patterntypescriptangularCritical
Get all validation errors from Angular 2 FormGroup
Viewed 0 times
angularerrorsfromformgroupvalidationallget
Problem
Given this code:
How can I get all validation errors from
I'm writing unit tests and want to include the actual validation errors in the assert message.
this.form = this.formBuilder.group({
email: ['', [Validators.required, EmailValidator.isValid]],
hasAcceptedTerms: [false, Validators.pattern('true')]
});
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.
Solution
I met the same problem and for finding all validation errors and displaying them, I wrote this method:
Form name
It works in this way: we get all our controls from the form in format
It also can be changed for displaying validation errors on the template view, just replace
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]);
});
}
});
}Form name
productForm should be changed to your form instance name.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.It also can be changed for displaying validation errors on the template view, just replace
console.log(..) to what you need.Code Snippets
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]);
});
}
});
}Context
Stack Overflow Q#40680321, score: 256
Revisions (0)
No revisions yet.