UNPKG

1.49 kBPlain TextView Raw
1const DT_SEPARATOR = /t|\s/i
2const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
3const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i
4const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
5
6export default function validTimestamp(str: string, allowDate: boolean): boolean {
7 // http://tools.ietf.org/html/rfc3339#section-5.6
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
15function 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 // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
27 (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))
28 )
29}
30
31function 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 // leap second
42 (hr - tzH === 23 && min - tzM === 59 && sec === 60)
43 )
44}
45
46validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'