Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Commit

Permalink
format multiple error messages when validating
Browse files Browse the repository at this point in the history
  • Loading branch information
kspearrin committed Aug 2, 2018
1 parent 6f64c5c commit 49d3f22
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions src/angular/services/validation.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { Injectable } from '@angular/core';
import {
Injectable,
SecurityContext,
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

import { ToasterService } from 'angular2-toaster';
import {
BodyOutputType,
Toast,
ToasterService,
} from 'angular2-toaster';

import { I18nService } from '../../abstractions/i18n.service';

@Injectable()
export class ValidationService {
constructor(private toasterService: ToasterService, private i18nService: I18nService) { }
constructor(private toasterService: ToasterService, private i18nService: I18nService,
private sanitizer: DomSanitizer) { }

showError(data: any): string[] {
const defaultErrorMessage = this.i18nService.t('unexpectedError');
Expand All @@ -25,13 +34,29 @@ export class ValidationService {
}

data.validationErrors[key].forEach((item: string) => {
errors.push(item);
let prefix = '';
if (key.indexOf('[') > -1 && key.indexOf(']') > -1) {
const lastSep = key.lastIndexOf('.');
prefix = key.substr(0, lastSep > -1 ? lastSep : key.length) + ': ';
}
errors.push(prefix + item);
});
}
}

if (errors.length > 0) {
if (errors.length === 1) {
this.toasterService.popAsync('error', this.i18nService.t('errorOccurred'), errors[0]);
} else if (errors.length > 1) {
let errorMessage = '';
errors.forEach((e) => errorMessage += ('<p>' + this.sanitizer.sanitize(SecurityContext.HTML, e) + '</p>'));
const toast: Toast = {
type: 'error',
title: this.i18nService.t('errorOccurred'),
body: errorMessage,
bodyOutputType: BodyOutputType.TrustedHtml,
timeout: 5000 * errors.length,
};
this.toasterService.popAsync(toast);
}

return errors;
Expand Down

0 comments on commit 49d3f22

Please sign in to comment.