diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d9f704..84d83d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `isValidGuid` function to check whether a given string is a valid Guid + ### dependabot: \#31 Bump ip from 1.1.8 to 1.1.9 ## [0.4.0] - 2024-01-29 diff --git a/src/lib/guid.spec.ts b/src/lib/guid.spec.ts index bc9b6af..d6a48b1 100644 --- a/src/lib/guid.spec.ts +++ b/src/lib/guid.spec.ts @@ -1,4 +1,4 @@ -import { newGuid, emptyGuid } from "./guid"; +import { newGuid, emptyGuid, isValidGuid } from "./guid"; describe("guid tests", () => { test("newGuid", () => { @@ -8,4 +8,23 @@ describe("guid tests", () => { test("emptyGuid", () => { expect(emptyGuid).toBe("00000000-0000-0000-0000-000000000000"); }); + + test.each([ + [null as unknown as string, false], + [undefined as unknown as string, false], + [0 as unknown as string, false], + [10 as unknown as string, false], + [new Date() as unknown as string, false], + ["", false], + [" ", false], + ["507956c7-30b3-4401-9800-e5e7f8f3276X", false], + ["507956c7-30b3-4401-9800-e5e7f8f32761", true], + [newGuid(), true], + [emptyGuid, true], + ["3B467B14-CD99-4199-8E35-82B3C37182BA", true], + // MAX not recognized as guid > https://github.com/uuidjs/uuid/pull/714 + ["ffffffff-ffff-ffff-ffff-ffffffffffff", false], + ])("isValidGuid", (value, expected) => { + expect(isValidGuid(value)).toBe(expected); + }); }); diff --git a/src/lib/guid.ts b/src/lib/guid.ts index 131c5e2..630e350 100644 --- a/src/lib/guid.ts +++ b/src/lib/guid.ts @@ -8,6 +8,15 @@ export function newGuid() { return uuid.v4(); } +/** + * Check whether a string it is a valid Guid (version 4 UUID) + * @param str The string to test whether it is a valid Guid + * @returns A value indicating whether the string is a valid Guid + */ +export function isValidGuid(str: string) { + return uuid.validate(str); +} + /** * The empty Guid (an identifier containing all zeros) */