UNPKG

cheetah-framework

Version:

Cheetah Framework JS used in all our applications

122 lines (103 loc) 2.68 kB
/** * Cheetah errors bag */ export default function () { this.errors = {} /** * Determine if the collection has any errors. */ this.hasErrors = function () { return !_.isEmpty(this.errors) } /** * Determine if the collection has errors for a given field. */ this.has = function (field) { if (_.includes(field, '*')) { let match = false const regX = new RegExp('^' + field.replace('*', '[^\*]+'), 'gi') _.each(this.errors, (error, key) => { if (regX.test(key)) { match = key return false } }) return match } return _.indexOf(_.keys(this.errors), field) > -1 ? field : false } /** * Get all of the raw errors for the collection. */ this.all = function () { return this.errors } /** * Get all of the errors for the collection in a flat array. */ this.flatten = function () { return _.flatten(_.toArray(this.errors)) } /** * Return all matching errors */ this.getAll = function (path) { if (/\*$/.test(path)) { const regX = new RegExp('^' + path.replace('*', '[\\w]+(\\.[^\\d\\.]*[\\w])?$')) return Object.keys(this.errors).reduce((acc, key) => { if (regX.test(key)) { acc = acc.concat(this.errors[key]) } return acc }, []) } return this.get(path) } /** * Get the first error message for a given field. */ this.get = function (field) { const match = this.has(field) if (match !== false) { return this.errors[match].join(', ') } } /** * Set the raw errors for the collection. */ this.set = function (errors) { if (typeof errors === 'object') { this.errors = errors } else { this.errors = { 'form': ['Something went wrong. Please try again or contact customer support.'] } } } /** * Add error to a field. */ this.add = function (field, errors) { this.errors = { ...this.errors, [field]: typeof errors === 'string' ? [errors] : errors } } /** * Remove errors from the collection. */ this.forget = function (field) { if (typeof field === 'undefined') { this.errors = {} } else { Vue.delete(this.errors, field) if (_.includes(field, '*')) { const regX = new RegExp(field.replace('*', '[^\*]+'), 'gi') _.each(this.errors, (error, key) => { if (regX.test(key)) { Vue.delete(this.errors, key) } regX.lastIndex = 0 }) } } } }