|
1 | | -import { computed, createStore, deep, take } from 'dotto.x' |
2 | | -import { onSet } from 'dotto.x/lifecycle' |
| 1 | +import { computed, createAtom, take } from 'dotto.x' |
| 2 | +import { onChange } from 'dotto.x/lifecycle' |
| 3 | +import { get } from 'dotto.x/utils/get' |
3 | 4 |
|
4 | | -export const validator = (store, rules, config = {}) => { |
5 | | - let errorsStore = createStore({}) |
6 | | - let errors = deep(errorsStore) |
| 5 | +export const validator = (store, rules) => { |
| 6 | + let errors = createAtom({}) |
7 | 7 | let valid = computed(() => !Object.values(take(errors)).filter(a => a).length) |
8 | | - let container = rules.reduce( |
9 | | - (acc, { path, validators }) => ({ ...acc, [path]: validators }), |
10 | | - {} |
11 | | - ) |
12 | | - let destroy = onSet(store, ([path, value], { methods }) => { |
13 | | - let target = container[path] |
14 | | - if (!target) return |
15 | | - let reason |
16 | | - let hasError = target.some(rule => { |
17 | | - let res = rule(value, methods) |
18 | | - if (res) reason = res |
19 | | - return res |
20 | | - }) |
21 | 8 |
|
22 | | - errorsStore.set(path, reason) |
23 | | - if (hasError && config.abort) { |
24 | | - methods.abort() |
| 9 | + let destroy = onChange(store, (_, { methods }) => { |
| 10 | + for (let { path, validators } of rules) { |
| 11 | + let target = get(store.get(), path) |
| 12 | + let reason |
| 13 | + validators.some(rule => { |
| 14 | + let res = rule(target, methods) |
| 15 | + if (res) reason = res |
| 16 | + return res |
| 17 | + }) |
| 18 | + errors.set({ ...errors.get(), [path]: reason }) |
25 | 19 | } |
26 | 20 | }) |
27 | | - |
28 | 21 | return { errors, destroy, valid } |
29 | 22 | } |
0 commit comments