UNPKG

jet-validators

Version:

Fast, zero-dependency TypeScript validators and utilities for runtime checks, parsing, and lightweight object schema validation.

72 lines (71 loc) 2.47 kB
import { markSafe } from '../utils/parseObject/mark-safe.js'; const DEFAULT_ERROR_MESSAGE = (value, reason) => `The value "${value}" failed to pass string validation. Reason: <${reason}>`; export function isValidString(options) { return isValidStringCore(options, false, false); } export function isOptionalValidString(options) { return isValidStringCore(options, true, false); } export function isNullableValidString(options) { return isValidStringCore(options, false, true); } export function isNullishValidString(options) { return isValidStringCore(options, true, true); } function isValidStringCore(options, optional, nullable) { const { regex, throws = false, errorMessage = DEFAULT_ERROR_MESSAGE, } = options; let handleFailed; if (throws) { handleFailed = (value, reason) => { throw new Error(errorMessage(value, reason)); }; } else { handleFailed = () => false; } let minLength = 0, maxLength, explicitEmptyStringAllowed = false; if ('length' in options && options.length !== undefined) { minLength = options.length; maxLength = options.length; } else { if ('minLength' in options && options.minLength !== undefined && options.minLength >= 0) { minLength = options.minLength; explicitEmptyStringAllowed = minLength === 0; } if ('maxLength' in options && options.maxLength !== undefined && options.maxLength >= 0) { maxLength = options.maxLength; } } const isValidString = (arg) => { if (arg === undefined) { return optional ? true : handleFailed(arg, 'optional'); } if (arg === null) { return nullable ? true : handleFailed(arg, 'nullable'); } if (typeof arg !== 'string') { return handleFailed(arg, 'not-string'); } if (arg === '' && explicitEmptyStringAllowed) { return true; } if (arg.length < minLength) { return handleFailed(arg, 'min-length'); } if (maxLength !== undefined && arg.length > maxLength) { return handleFailed(arg, 'max-length'); } if (regex !== undefined) { if (!regex.test(arg)) return handleFailed(arg, 'regex'); } return true; }; markSafe(isValidString); return isValidString; }