@greatefue/generate_form_errors
Version:
Generate HTML error messages for invalid Angular FormGroup fields with labels
74 lines (64 loc) • 1.97 kB
JavaScript
/**
* GENERATE_FORM_ERRORS
* Generate a HTML error message listing invalid form fields.
*
* @param {Object} FORM - Angular FormGroup or plain object of controls.
* @param {Object} LABEL_MAP - mapping from field keys to human-readable labels.
* @returns {string} HTML string with error message or empty string.
*/
function GENERATE_FORM_ERRORS(FORM, LABEL_MAP) {
LABEL_MAP = LABEL_MAP || {};
const INVALID_FORM_FIELDS = [];
const CONTROLS = FORM && FORM.controls ? FORM.controls : FORM || {};
Object.keys(CONTROLS).forEach(KEY => {
let CONTROL;
if (FORM && typeof FORM.get === 'function') {
CONTROL = FORM.get(KEY);
} else {
CONTROL = CONTROLS[KEY];
}
const IS_INVALID =
CONTROL === true ||
(CONTROL && (
CONTROL.invalid === true ||
CONTROL.isInvalid === true ||
(CONTROL.errors && Object.keys(CONTROL.errors).length > 0)
));
if (IS_INVALID) {
const FIELD_NAME = LABEL_MAP[KEY] || KEY;
INVALID_FORM_FIELDS.push(
`<a href="javascript:void(0);">
<span class="py-1 px-2 fs-12 bg-soft-danger rounded text-danger fw-medium">
${ESCAPE_HTML(FIELD_NAME)}
</span>
</a>`
);
}
});
return INVALID_FORM_FIELDS.length
? `Please fill in the following required fields: ${INVALID_FORM_FIELDS.join(', ')}`
: '';
}
/**
* ESCAPE_HTML
* Safely escape HTML characters in strings.
*
* @param {string} STR
* @returns {string}
*/
function ESCAPE_HTML(STR) {
if (typeof STR !== 'string') return String(STR);
return STR
.replace(/&/g, '&')
.replace(/</g,'<')
.replace(/>/g,'>')
.replace(/"/g,'"')
.replace(/'/g,''');
}
const GREAT_EFUE = {
GENERATE_FORM_ERRORS
};
module.exports = { GREAT_EFUE };
module.exports.GENERATE_FORM_ERRORS = GENERATE_FORM_ERRORS;
module.exports.default = GENERATE_FORM_ERRORS;
;