opnform-host-nginx/client/composables/lib/vForm/Errors.js

75 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-12-14 16:53:05 +01:00
function arrayWrap(value) {
return Array.isArray(value) ? value : [value]
2023-12-14 16:53:05 +01:00
}
export default class Errors {
constructor() {
this.errors = {}
2023-12-14 16:53:05 +01:00
}
set(field, messages = undefined) {
if (typeof field === "object") {
this.errors = field
2023-12-14 16:53:05 +01:00
} else {
this.set({ ...this.errors, [field]: arrayWrap(messages) })
2023-12-14 16:53:05 +01:00
}
}
all() {
return this.errors
2023-12-14 16:53:05 +01:00
}
has(field) {
return Object.prototype.hasOwnProperty.call(this.errors, field)
2023-12-14 16:53:05 +01:00
}
hasAny(...fields) {
return fields.some((field) => this.has(field))
2023-12-14 16:53:05 +01:00
}
any() {
return Object.keys(this.errors).length > 0
2023-12-14 16:53:05 +01:00
}
get(field) {
if (this.has(field)) {
return this.getAll(field)[0]
2023-12-14 16:53:05 +01:00
}
}
getAll(field) {
return arrayWrap(this.errors[field] || [])
2023-12-14 16:53:05 +01:00
}
only(...fields) {
const messages = []
2023-12-14 16:53:05 +01:00
fields.forEach((field) => {
const message = this.get(field)
2023-12-14 16:53:05 +01:00
if (message) {
messages.push(message)
2023-12-14 16:53:05 +01:00
}
})
2023-12-14 16:53:05 +01:00
return messages
2023-12-14 16:53:05 +01:00
}
flatten() {
return Object.values(this.errors).reduce((a, b) => a.concat(b), [])
2023-12-14 16:53:05 +01:00
}
clear(field = undefined) {
const errors = {}
2023-12-14 16:53:05 +01:00
if (field) {
Object.keys(this.errors).forEach((key) => {
if (key !== field) {
errors[key] = this.errors[key]
2023-12-14 16:53:05 +01:00
}
})
2023-12-14 16:53:05 +01:00
}
this.set(errors)
2023-12-14 16:53:05 +01:00
}
}