Skip to content

Commit

Permalink
Add isValidGuid function (#35)
Browse files Browse the repository at this point in the history
This PR implements a wrapper function `isValidGuid` able to validate a
string to check whether it is guid uuid v4.
Closes #34
  • Loading branch information
Michele-Masciave authored Mar 15, 2024
1 parent 3d16a63 commit 39c68b3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion src/lib/guid.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { newGuid, emptyGuid } from "./guid";
import { newGuid, emptyGuid, isValidGuid } from "./guid";

describe("guid tests", () => {
test("newGuid", () => {
Expand All @@ -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);
});
});
9 changes: 9 additions & 0 deletions src/lib/guid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
*/
Expand Down

0 comments on commit 39c68b3

Please sign in to comment.