verificator
Version:
Client and server-side validation JavaScript library
48 lines (47 loc) • 1.19 kB
JavaScript
import { addError, removeError, clearErrors } from './actions';
export default class ErrorBag {
constructor(store) {
this._store = store;
}
add(key, message) {
this._store.dispatch(addError(key, message));
return this;
}
remove(key) {
this._store.dispatch(removeError(key));
return this;
}
clear() {
this._store.dispatch(clearErrors());
return this;
}
first(key) {
const [messages] = this.get(key);
return messages;
}
has(key) {
return this.get(key).length > 0;
}
get(key) {
const { errors } = this._store.getState();
if (key in errors) {
return errors[key];
}
return [];
}
all() {
const { errors } = this._store.getState();
return Object.keys(errors).reduce((value, key) => {
return value.concat(this.get(key));
}, []);
}
any() {
return this.count() > 0;
}
count() {
const { errors } = this._store.getState();
return Object.keys(errors).reduce((value, key) => {
return value + errors[key].length;
}, 0);
}
}