-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
validator.ts
39 lines (35 loc) · 1.01 KB
/
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
import { parseValidator } from './parser'
import { IValidateResults, Validator, IValidatorOptions } from './types'
import {
registerValidateFormats,
registerValidateLocale,
registerValidateRules,
} from './registry'
import locales from './locale'
import formats from './formats'
import rules from './rules'
registerValidateRules(rules)
registerValidateLocale(locales)
registerValidateFormats(formats)
export const validate = async <Context = any>(
value: any,
validator: Validator<Context>,
options?: IValidatorOptions<Context>
): Promise<IValidateResults> => {
const validates = parseValidator(validator, options)
const results: IValidateResults = {
error: [],
success: [],
warning: [],
}
for (let i = 0; i < validates.length; i++) {
const result = await validates[i](value, options?.context)
const { type, message } = result
results[type] = results[type] || []
if (message) {
results[type].push(message)
if (options?.validateFirst) break
}
}
return results
}