1 | const DT_SEPARATOR = /t|\s/i
|
2 | const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
|
3 | const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i
|
4 | const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
5 |
|
6 | export default function validTimestamp(str: string, allowDate: boolean): boolean {
|
7 |
|
8 | const dt: string[] = str.split(DT_SEPARATOR)
|
9 | return (
|
10 | (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
|
11 | (allowDate && dt.length === 1 && validDate(dt[0]))
|
12 | )
|
13 | }
|
14 |
|
15 | function validDate(str: string): boolean {
|
16 | const matches: string[] | null = DATE.exec(str)
|
17 | if (!matches) return false
|
18 | const y: number = +matches[1]
|
19 | const m: number = +matches[2]
|
20 | const d: number = +matches[3]
|
21 | return (
|
22 | m >= 1 &&
|
23 | m <= 12 &&
|
24 | d >= 1 &&
|
25 | (d <= DAYS[m] ||
|
26 |
|
27 | (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))
|
28 | )
|
29 | }
|
30 |
|
31 | function validTime(str: string): boolean {
|
32 | const matches: string[] | null = TIME.exec(str)
|
33 | if (!matches) return false
|
34 | const hr: number = +matches[1]
|
35 | const min: number = +matches[2]
|
36 | const sec: number = +matches[3]
|
37 | const tzH: number = +(matches[4] || 0)
|
38 | const tzM: number = +(matches[5] || 0)
|
39 | return (
|
40 | (hr <= 23 && min <= 59 && sec <= 59) ||
|
41 |
|
42 | (hr - tzH === 23 && min - tzM === 59 && sec === 60)
|
43 | )
|
44 | }
|
45 |
|
46 | validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'
|