-
Notifications
You must be signed in to change notification settings - Fork 3
/
vue-tiny-validator.ts
218 lines (189 loc) · 4.59 KB
/
vue-tiny-validator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import {
ComputedRef,
Ref,
ref,
isRef,
inject,
provide,
reactive,
computed,
onBeforeUnmount,
} from 'vue'
const FormSymbol = Symbol('Form')
export type FormError = {
identifier?: string
value: unknown
message: string
}
export type FormField = {
validate: () => boolean
validateAsync: () => Promise<boolean>
reset: () => void
error: Ref<string>
identifier?: string
value: Ref<unknown>
}
export type FormContext = {
registerField: (field: FormField) => void
unregisterField: (field: FormField) => void
}
export type FormRule = (value: any) => unknown
export type FieldOptions = {
value: Ref<any> | ComputedRef<any> | (() => any)
rules:
| FormRule[]
| Ref<FormRule[]>
| ComputedRef<FormRule[]>
| (() => FormRule[])
identifier?: string
form?: { [FormSymbol]: FormContext }
}
function checkRulesSync(value: unknown, rules: FormRule[]) {
for (const rule of rules) {
const result = rule(value)
if (result !== true) {
return result
}
}
}
async function checkRulesAsync(value: unknown, rules: FormRule[]) {
for (const rule of rules) {
try {
const result = await rule(value)
if (result !== true) {
return result
}
} catch (error) {
return error.message
}
}
}
/**
* Validates a field value against a list of rules.
*
* @param options
* @param options.value The model-value of the field
* @param options.rules List of rules that the value needs to fulfill
* @param options.identifier Optional identifier for this field, passed later to the form
* @param options.form Optional form context when this field is not a child of the form
*/
export function useField({ value, rules, identifier, form }: FieldOptions) {
const computedValue = isRef(value) ? value : computed(value)
const computedRules = isRef(rules)
? rules
: computed(rules instanceof Function ? rules : () => rules)
const error = ref('')
/**
* Reset the error message.
*/
const reset = () => {
error.value = ''
}
const validateRulesResult = (result: unknown) => {
if (result && typeof result === 'string') {
error.value = result
return false
}
reset()
return true
}
/**
* Validate field value against rules. Returns true if valid.
*/
const validate = () =>
validateRulesResult(
checkRulesSync(computedValue.value, computedRules.value)
)
/**
* Validate field value against rules asynchronously. Resolves to true if valid.
*/
const validateAsync = () =>
checkRulesAsync(computedValue.value, computedRules.value).then(
validateRulesResult
)
const context = inject<FormContext | undefined>(
FormSymbol,
form?.[FormSymbol]
)
if (context) {
const field = {
validate,
validateAsync,
reset,
error,
identifier,
value: computedValue,
}
context.registerField(field)
onBeforeUnmount(() => context.unregisterField(field))
}
return {
validate,
validateAsync,
error: computed(() => error.value),
reset,
}
}
/**
* Validates all the nested field components.
*/
export function useForm() {
const fields = reactive(new Set() as Set<FormField>)
const context = {
registerField(field: FormField) {
fields.add(field)
},
unregisterField(field: FormField) {
fields.delete(field)
},
} as FormContext
provide(FormSymbol, context)
/**
* Form context to pass it to non-nested fields.
*/
const form = { [FormSymbol]: context }
const errors = computed(() =>
[...fields]
.filter((field) => !!field.error)
.map(({ error, value, identifier }) => ({
// Refs are lost after values enter the reactive Set (?)
message: (error as unknown) as string,
value: value as unknown,
identifier,
}))
)
/**
* Reset the errors.
*/
const reset = () => {
for (const field of fields) {
field.reset()
}
}
/**
* Validate all nested fields against rules. Returns true if all fields are valid.
*/
const validate = () => {
reset()
for (const field of fields) {
field.validate()
}
return errors.value.length === 0
}
/**
* Validate all nested fields against rules asynchronously. Resolves to true if all fields are valid.
*/
const validateAsync = async () => {
reset()
await Promise.all([...fields].map((field) => field.validateAsync()))
return errors.value.length === 0
}
return {
validate,
validateAsync,
errors,
reset,
form,
isValid: computed(() => errors.value.length === 0),
}
}