UNPKG

class-validator-extended

Version:
51 lines (50 loc) 2.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MAX_DURATION = void 0; exports.MaxDuration = MaxDuration; const class_validator_1 = require("class-validator"); const create_duration_1 = require("../create-duration"); const is_valid_duration_1 = require("../is-valid-duration"); const max_duration_predicate_1 = require("./max-duration.predicate"); /** @hidden */ exports.MAX_DURATION = 'maxDuration'; function message(options) { return `a valid Dayjs duration ${(options === null || options === void 0 ? void 0 : options.inclusive) ? 'equal to or not longer than' : 'not longer than'} $constraint1`; } /** * Checks if the given value is a valid Dayjs duration not longer than `maximum`. * * The minimum can be given as either: * - a Dayjs duration * - an ISO 8601 string, e.g. `"PT1H"` * - a units object, e.g. `{ hour: 1, minute: 30 }` * - a time/unit tuple, e.g. `[1, 'hour]` * * #### Example * ```typescript * // Ensure the value is a duration at most 1 hour long * @MaxDuration([1, 'hour'], { inclusive: true }) * value: Duration * ``` * * @category Dayjs * @param maximum The maximum allowed value. * @param options * Accepts the following options (in addition to generic class-validator options): * - `inclusive: boolean = false` * If true, allow the `maximum` duration as well. */ function MaxDuration(maximum, options) { const max = (0, create_duration_1.createDuration)(maximum); if (!(0, is_valid_duration_1.isValidDuration)(max)) { throw new TypeError('Parameter "maximum" must be a valid Dayjs duration'); } return (0, class_validator_1.ValidateBy)({ name: exports.MAX_DURATION, constraints: [max.toISOString()], validator: { validate: (value, _arguments) => (0, max_duration_predicate_1.maxDuration)(value, max, { inclusive: options === null || options === void 0 ? void 0 : options.inclusive }), defaultMessage: (0, class_validator_1.buildMessage)(eachPrefix => `${eachPrefix}$property must be ${message(options)}`, options), }, }, options); }