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;
}
}
I took it from Deborahk and modified it a little bit.