-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathexclusive-between.ts
More file actions
70 lines (63 loc) · 2.08 KB
/
exclusive-between.ts
File metadata and controls
70 lines (63 loc) · 2.08 KB
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
import { Boxed, unbox, ValidationErrors } from 'ngrx-forms';
export interface ExclusiveBetweenValidationError {
min: number;
max: number;
actual: number;
}
// @ts-ignore
declare module 'ngrx-forms/src/state' {
export interface ValidationErrors {
exclusiveBetween?: ExclusiveBetweenValidationError;
}
}
/**
* A validation function that requires the value to be between the given min and max values.
* Considers `null`, `undefined` and non-numeric values as valid. Combine this function with the `required`
* validation function if `null` or `undefined` should be considered invalid.
*
* The validation error returned by this validation function has the following shape:
*
```typescript
{
exclusiveBetween: {
min: number;
max: number;
actual: number;
};
}
```
*
* Usually you would use this validation function in conjunction with the `validate`
* update function to perform synchronous validation in your reducer:
*
```typescript
updateGroup<MyFormValue>({
amount: validate(exclusiveBetween(0, 100)),
})
```
*
* Note that this function is generic to allow the compiler to properly infer the type
* of the `validate` function for both optional and non-optional controls.
*/
export function exclusiveBetween(min: number, max: number) {
// tslint:disable-next-line:strict-type-predicates (guard for users without strict type checking)
if (min === null || min === undefined || max === null || max === undefined) {
throw new Error(`The exclusiveBetween Validation function requires the min and max parameters to be a non-null number, got ${min} and ${max}!`);
}
return <T extends number | Boxed<number> | null | undefined>(value: T): ValidationErrors => {
value = unbox(value) as number | null | undefined as T;
if (value === null || value === undefined || typeof value !== 'number') {
return {};
}
if (min < value && value < max) {
return {};
}
return {
exclusiveBetween: {
min,
max,
actual: value as number,
},
};
};
}