bguard
Version:
**bguard** is a powerful, flexible, and type-safe validation library for TypeScript. It allows developers to define validation schemas for their data structures and ensures that data conforms to the expected types and constraints.
1 lines • 2.17 kB
Source Map (JSON)
{"version":3,"sources":["../src/asserts/string/validUrl.ts"],"sourcesContent":["import type { ExceptionContext, RequiredValidation } from '../../core';\nimport { setToDefaultLocale } from '../../translationMap';\n\nconst validUrlErrorMessage = 'The received value is not a valid URL';\nconst validUrlErrorKey = 's:validUrl';\n\nconst urlRegex = /^(http:\\/\\/|https:\\/\\/)([a-zA-Z0-9\\-.]+)(:\\d+)?(\\/[^\\s]*)?$/;\n\n/**\n * @description Asserts that the string value is a valid URL with optional protocol validation.\n * @param {string} [protocol] The protocol that the URL must start with (e.g., 'http'). If not provided, any URL starting with 'http://' or 'https://' is considered valid.\n * @returns {RequiredValidation} A validation function that takes a received string and an exception context.\n * @throws {ValidationError} if the received value does not match the expected URL pattern.\n * @example\n * const schema = string().custom(validUrl()); // Validates any URL starting with 'http://' or 'https://'\n * parseOrFail(schema, 'http://example.com'); // Valid\n * parseOrFail(schema, 'https://example.com'); // Valid\n * parseOrFail(schema, 'ftp://example.com'); // Throws an error\n * parseOrFail(schema, 'http:example.com'); // Throws an error\n *\n * @translation Error Translation Key = 's:url'\n */\nexport const validUrl =\n (protocol?: string): RequiredValidation =>\n (received: string, ctx: ExceptionContext) => {\n let regex = urlRegex;\n if (protocol) {\n regex = new RegExp(`^${protocol}:\\\\/\\\\/([a-zA-Z0-9\\\\-\\\\.]+)(:[0-9]+)?(\\\\/[^\\\\s]*)?$`);\n }\n\n if (!regex.test(received)) {\n ctx.addIssue('Invalid URL', received, validUrlErrorKey);\n }\n };\n\nvalidUrl.key = validUrlErrorKey;\nvalidUrl.message = validUrlErrorMessage;\nsetToDefaultLocale(validUrl);\n"],"mappings":";;;;;AAGA,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AAgBV,IAAM,WACX,CAAC,aACD,CAAC,UAAkB,QAA0B;AAC3C,MAAI,QAAQ;AACZ,MAAI,UAAU;AACZ,YAAQ,IAAI,OAAO,IAAI,QAAQ,qDAAqD;AAAA,EACtF;AAEA,MAAI,CAAC,MAAM,KAAK,QAAQ,GAAG;AACzB,QAAI,SAAS,eAAe,UAAU,gBAAgB;AAAA,EACxD;AACF;AAEF,SAAS,MAAM;AACf,SAAS,UAAU;AACnB,mBAAmB,QAAQ;","names":[]}