angular-super-validator
Version:
Angular4 Deep Form Validator
113 lines • 3.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var forms_1 = require("@angular/forms");
var lodash_1 = require("lodash");
/**
* Form Helper
*
*
*/
var SuperForm = /** @class */ (function () {
function SuperForm() {
}
/**
* Get all errors from a Abstract Control
* -- loop all children
* -- eliminate keys that don't have errors
*
*
* @param {AbstractControl} formEl
* @returns {{}}
*/
SuperForm.getAllErrors = function (formEl) {
var errs = {};
if (formEl instanceof forms_1.FormGroup) {
// -->Get: all errors
errs = lodash_1.mapValues(formEl.controls, function (vv, cc) {
var err = SuperForm.getAllErrors(vv);
return (err) ? err : null;
});
// -->Eliminate: null values
lodash_1.keys(errs)
.map(function (k) {
if (!errs[k])
delete errs[k];
if (lodash_1.isArray(errs[k]) && errs[k].length === 0)
delete errs[k];
});
}
else if (formEl instanceof forms_1.FormArray) {
errs = formEl.controls.map(function (el) {
return SuperForm.getAllErrors(el);
})
.filter(function (s) { return lodash_1.isPlainObject(s); })
.filter(function (s) { return lodash_1.keys(s).length; });
}
else if (formEl instanceof forms_1.FormControl) {
errs = formEl.errors || null;
}
return errs;
};
/**
* List the errors in a flat map
*
*
* @param {AbstractControl} formEl
* @param {string} path
* @returns {{}}
*/
SuperForm.getAllErrorsFlat = function (formEl, path) {
if (path === void 0) { path = ''; }
var errs2 = {};
var walk = function (fEl, p) {
var errs = {};
if (fEl instanceof forms_1.FormGroup || fEl instanceof forms_1.FormArray) {
var ks = lodash_1.keys(fEl.controls);
var isArr_1 = fEl instanceof forms_1.FormArray;
ks.map(function (k) {
var newKey = (isArr_1) ? '[' + k + ']' : k;
var newPath = (isArr_1) ? (p) ? p + newKey : newKey : (p) ? p + '.' + newKey : newKey;
var err = walk(fEl.get(k), newPath);
errs[newPath] = (err) ? err : null;
});
// -->Eliminate: null values
lodash_1.keys(errs)
.map(function (k) {
if (!errs[k])
delete errs[k];
if (lodash_1.isArray(errs[k]) && errs[k].length === 0)
delete errs[k];
});
}
else if (fEl instanceof forms_1.FormControl) {
errs = fEl.errors || null;
if (errs)
errs2[p] = errs;
}
};
walk(formEl, path);
return errs2;
};
/**
* Flatten a deep object
*
* @param object
* @returns {{} & any}
*/
SuperForm.flatten = function (object, sep) {
if (sep === void 0) { sep = '/'; }
return Object.assign.apply(Object, [{}].concat(function _flatten(objectBit, path) {
if (path === void 0) { path = ''; }
return [].concat.apply([], Object.keys(objectBit)
.map(function (key) {
return typeof objectBit[key] === 'object' ?
_flatten(objectBit[key], "" + (path ? path + sep : path) + key)
: (_a = {}, _a["" + (path ? path + sep : path) + key] = objectBit[key], _a);
var _a;
}));
}(object)));
};
return SuperForm;
}());
exports.SuperForm = SuperForm;
//# sourceMappingURL=superForm.js.map