-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
validation.ts
88 lines (75 loc) · 2.15 KB
/
validation.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
/**
* Form Schema
*/
export type ReservedFormStateKeys =
| 'valid'
| 'invalid'
| 'untouched'
| 'touched'
| 'pristine'
| 'dirty';
export type ReservedFormFieldKeys = 'value' | 'validators';
export type ReservedFormKeys = ReservedFormFieldKeys | ReservedFormStateKeys | 'errors';
export type AllowedFormKeys = Exclude<string, ReservedFormKeys>;
export type ValidateOnEvent = 'blur' | 'change' | 'input' | 'submit';
export type FormValue = FormValue[] | object | string | number | boolean | null | undefined;
export type FormValidatorFn<T = Record<string, any>, S extends Form = Form> = (
value: FormValue,
options: T & {
schema?: ResolvedFormSchema<S> | FormSchema<S>;
path: string;
}
) => boolean | Promise<boolean>;
export interface FormValidator {
name: string;
[key: string]: any;
}
export type FormField<V> = {
value?: V;
validateOn?: ValidateOnEvent;
validators?: Array<FormValidator | string>;
};
export type Form = Record<string, any>;
export type FormSchema<T extends Form> = {
[K in keyof T]: T[K] extends infer U
? U extends Array<infer V>
? U extends FormField<V[]>
? FormField<V[]>
: V extends object
? FormSchema<V>[]
: FormField<U[number]>[] | FormField<U>
: U extends object
? FormSchema<U>
: FormField<U>
: never;
};
/**
* Resolved Form Schema
*/
export interface FormError {
name: string;
message: string;
path: string;
}
export interface FormState {
valid: boolean;
invalid: boolean;
untouched: boolean;
touched: boolean;
pristine: boolean;
dirty: boolean;
errors: FormError[];
}
export type ResolvedFormField<V> = {
value: V;
validators: Array<FormValidator | string>;
} & FormState;
export type ResolvedFormSchema<T extends Form> = {
[K in keyof T]: T[K] extends Array<infer V>
? V extends object
? ResolvedFormSchema<V>[]
: ResolvedFormField<T[K][number]>[]
: T[K] extends object
? ResolvedFormSchema<T[K]>
: ResolvedFormField<T[K]>;
} & FormState;