-
Notifications
You must be signed in to change notification settings - Fork 1
/
fieldHelper.ts
40 lines (32 loc) · 1.05 KB
/
fieldHelper.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
import { isArray, isEqual, isObject, isUndefined, reduce } from "lodash";
import { TFieldValue, TValidator } from "./interfaces";
export const isFieldDirty = (value: TFieldValue, defaultValue: string) => {
return !isEqual(value, defaultValue);
};
export const validateField = (value: string | boolean, validate?: TValidator | TValidator[]) => {
if (isUndefined(validate)) {
return;
}
if (isArray(validate)) {
return combineValidators(validate)(value);
}
if (typeof validate === "function") {
return validate(value);
}
return;
};
export const combineValidators = (validators: TValidator[]) => {
return (value: TFieldValue): string | undefined => {
return reduce(
validators,
(error: string | undefined, validator) => {
return error || validateField(value, validator);
},
undefined,
);
};
};
export const pickValue = (evtOrValue: MouseEvent | TFieldValue) => {
const isEvent = isObject(evtOrValue) && (evtOrValue as any).target;
return isEvent ? (evtOrValue as any).target.value : evtOrValue;
};