cheetah-framework
Version:
Cheetah Framework JS used in all our applications
103 lines (88 loc) • 2.15 kB
JavaScript
/**
* 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))
}
/**
* 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
})
}
}
}
}