UNPKG

@backland/schema

Version:

TypeScript schema declaration and validation library with static type inference

56 lines (55 loc) 1.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StringField = void 0; var _utils = require("@backland/utils"); var _FieldType = require("./FieldType"); var _FieldTypeErrors = require("./FieldTypeErrors"); class StringField extends _FieldType.FieldType { constructor(def = {}) { super({ def: def, name: 'string' }); const { min, max, regex } = def; (0, _utils.expectedType)({ max, min }, 'number', true); (0, _utils.expectedType)({ regex }, 'array', true); const regExp = regex && new RegExp(regex[0], regex[1]); this.parse = this.applyParser({ parse(input) { (0, _utils.expectedType)({ value: input }, 'string'); if (regExp && !regExp.test(input) && regex) { throw new _FieldTypeErrors.FieldTypeError(`regexMismatch`, { input, regex: regExp.toString() }); } const length = input.length; if (max !== undefined && length > max) { throw new _FieldTypeErrors.FieldTypeError('maxSize', `${length} is more than the max string length ${max}.`); } if (min !== undefined && length < min) { throw new _FieldTypeErrors.FieldTypeError('minSize', `${length} is less than the min string length ${min}.`); } return input; } }); } static create = def => { return new StringField(def); }; } exports.StringField = StringField; //# sourceMappingURL=StringField.js.map