UNPKG

3.06 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.stringExtensions = void 0;
4const js_lib_1 = require("@naturalcycles/js-lib");
5function stringExtensions(joi) {
6 return {
7 type: 'string',
8 base: joi.string(),
9 messages: {
10 'string.dateString': '"{{#label}}" must be an ISO8601 date (yyyy-mm-dd)',
11 'string.dateStringMin': '"{{#label}}" must be not earlier than {{#min}}',
12 'string.dateStringMax': '"{{#label}}" must be not later than {{#max}}',
13 'string.dateStringCalendarAccuracy': '"{{#label}}" must be a VALID calendar date',
14 'string.stripHTML': '"{{#label}}" must NOT contain any HTML tags',
15 },
16 rules: {
17 dateString: {
18 method(min, max) {
19 return this.$_addRule({
20 name: 'dateString',
21 args: { min, max },
22 });
23 },
24 args: [
25 {
26 name: 'min',
27 ref: true,
28 assert: v => typeof v === 'string',
29 message: 'must be a string',
30 },
31 {
32 name: 'max',
33 ref: true,
34 assert: v => typeof v === 'string',
35 message: 'must be a string',
36 },
37 ],
38 validate(v, helpers, args) {
39 // console.log('dateString validate called', {v, args})
40 let err;
41 let { min, max } = args;
42 // Today allows +-14 hours gap to account for different timezones
43 if (max === 'today') {
44 max = (0, js_lib_1.localTime)().add(14, 'hour').toISODate();
45 }
46 if (min === 'today') {
47 min = (0, js_lib_1.localTime)().subtract(14, 'hour').toISODate();
48 }
49 // console.log('min/max', min, max)
50 const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);
51 if (!m || m.length <= 1) {
52 err = 'string.dateString';
53 }
54 else if (min && v < min) {
55 err = 'string.dateStringMin';
56 }
57 else if (max && v > max) {
58 err = 'string.dateStringMax';
59 }
60 else if (!js_lib_1.LocalDate.isValid(v)) {
61 // todo: replace with another regex (from ajv-validators) for speed
62 err = 'string.dateStringCalendarAccuracy';
63 }
64 if (err) {
65 return helpers.error(err, args);
66 }
67 return v; // validation passed
68 },
69 },
70 },
71 };
72}
73exports.stringExtensions = stringExtensions;