-
Notifications
You must be signed in to change notification settings - Fork 1
/
date.ts
64 lines (61 loc) · 1.42 KB
/
date.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
import { fromInstance } from "../composite/object";
import { refine, refineWithMetainformation } from "../refine";
import { Schema, coerce } from "../schema";
import { ValidationIssue } from "../validation";
export function date(
issues?: Partial<{
required: string;
wrongType: string;
isNan: string;
}>
): Schema<Date, Date, { type: "object"; instance: string }> {
return refine(fromInstance(Date, issues), (d) => {
if (Number.isNaN(d.valueOf())) {
return new ValidationIssue("invalid_date", issues?.isNan, d);
}
});
}
export function coercedDate(
issues?: Partial<{
required: string;
wrongType: string;
isNan: string;
}>
): Schema<Date, Date, { type: "object"; instance: string }> {
return coerce(date(issues), (v) => {
if (typeof v === "string" || typeof v === "number") {
return new Date(v);
}
return v;
});
}
export function before<O, M>(
schema: Schema<Date, O, M>,
value: Date,
issue?: string
) {
return refineWithMetainformation(
schema,
(v) => {
if (v >= value) {
return new ValidationIssue("before", issue, v, value);
}
},
{ max: value }
);
}
export function after<O, M>(
schema: Schema<Date, O, M>,
value: Date,
issue?: string
) {
return refineWithMetainformation(
schema,
(v) => {
if (v <= value) {
return new ValidationIssue("after", issue, v, value);
}
},
{ min: value }
);
}