UNPKG

@naturalcycles/nodejs-lib

Version:
74 lines (73 loc) 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringExtensions = void 0; const js_lib_1 = require("@naturalcycles/js-lib"); function stringExtensions(joi) { return { type: 'string', base: joi.string(), messages: { 'string.dateString': '"{{#label}}" must be an ISO8601 date (yyyy-mm-dd)', 'string.dateStringMin': '"{{#label}}" must be not earlier than {{#min}}', 'string.dateStringMax': '"{{#label}}" must be not later than {{#max}}', 'string.dateStringCalendarAccuracy': '"{{#label}}" must be a VALID calendar date', 'string.stripHTML': '"{{#label}}" must NOT contain any HTML tags', }, rules: { dateString: { method(min, max) { return this.$_addRule({ name: 'dateString', args: { min, max }, }); }, args: [ { name: 'min', ref: true, assert: v => typeof v === 'string', message: 'must be a string', }, { name: 'max', ref: true, assert: v => typeof v === 'string', message: 'must be a string', }, ], validate(v, helpers, args) { // console.log('dateString validate called', {v, args}) let err; let { min, max } = args; // Today allows +-14 hours gap to account for different timezones if (max === 'today') { max = (0, js_lib_1.localTime)().add(14, 'hour').toISODate(); } if (min === 'today') { min = (0, js_lib_1.localTime)().subtract(14, 'hour').toISODate(); } // console.log('min/max', min, max) const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v); if (!m || m.length <= 1) { err = 'string.dateString'; } else if (min && v < min) { err = 'string.dateStringMin'; } else if (max && v > max) { err = 'string.dateStringMax'; } else if (!js_lib_1.LocalDate.isValid(v)) { // todo: replace with another regex (from ajv-validators) for speed err = 'string.dateStringCalendarAccuracy'; } if (err) { return helpers.error(err, args); } return v; // validation passed }, }, }, }; } exports.stringExtensions = stringExtensions;