-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
between.ts
35 lines (27 loc) · 870 Bytes
/
between.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
import { SimpleValidationRuleFunction } from '../../shared';
import { isEmpty } from './utils';
type BetweenParams = [string | number, string | number] | { min: number | string; max: number | string };
function getParams(params: BetweenParams) {
if (!params) {
return {
min: 0,
max: 0,
};
}
if (Array.isArray(params)) {
return { min: params[0], max: params[1] };
}
return params;
}
const betweenValidator: SimpleValidationRuleFunction<unknown, BetweenParams> = (value, params): boolean => {
if (isEmpty(value)) {
return true;
}
const { min, max } = getParams(params);
if (Array.isArray(value)) {
return value.every(val => !!betweenValidator(val, { min, max }));
}
const valueAsNumber = Number(value);
return Number(min) <= valueAsNumber && Number(max) >= valueAsNumber;
};
export default betweenValidator;