Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active April 15, 2018 19:13
Show Gist options
  • Save surferxo3/dfde629413561d988fb89efb700d6ddf to your computer and use it in GitHub Desktop.
Save surferxo3/dfde629413561d988fb89efb700d6ddf to your computer and use it in GitHub Desktop.
Get all validation errors from Angular 2+ FormArray and FormGroup in human readable form
import {NgModule, Injectable} from '@angular/core';
import {AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors} from '@angular/forms';
import {mapValues, filter, isArray, isEmpty, isPlainObject, keys, findKey} from 'lodash';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: [],
})
@Injectable()
export class SharedModule {
public static humanize(str: string): string {
return SharedModule.ucfirst(str.replace(/_/g, ' ').replace(/-/g, ' ').trim());
}
public static readableError(key: string, error: string, error_value: any): string {
if (error === 'required') {
error = SharedModule.humanize(key) + ' is required';
} else if (error === 'pattern') {
error = SharedModule.humanize(key) + ' is invalid';
} else if (error === 'minlength') {
error = SharedModule.humanize(key) + ' must be at least ' + error_value['requiredLength'] + ' characters long';
} else if (error === 'min') {
error = SharedModule.humanize(key) + ' must be greater than or equal to ' + error_value['min'];
} else if (error === 'max') {
error = SharedModule.humanize(key) + ' must be less than or equal to ' + error_value['max'];
}
return error;
}
public static getControlName(c: AbstractControl): string | null {
const formGroup = c.parent.controls;
//return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
return findKey(formGroup, c);
}
public static getAllErrors(formEl: AbstractControl, server_errors = {}): any {
let errs = {};
if (formEl instanceof FormGroup) {
// Get: all errors
errs = mapValues(formEl.controls, (vv, cc) => {
const err = this.getAllErrors(vv);
return (err) ? err : null;
});
// Eliminate: null values
keys(errs).map(k => {
if (!errs[k]) delete errs[k];
if (isEmpty(errs[k] || (isArray(errs[k]) && errs[k].length === 0))) delete errs[k];
});
} else if (formEl instanceof FormArray) {
errs = formEl.controls.map(el => {
return this.getAllErrors(el);
})
.filter(s => isPlainObject(s))
.filter(s => keys(s).length);
} else if (formEl instanceof FormControl) {
let controlErrors = <ValidationErrors>formEl.errors || null;
keys(controlErrors).map(k => {
errs = SharedModule.readableError(this.getControlName(formEl), k, controlErrors[k]);
});
}
return errs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment