Skip to content

Commit b57f44a

Browse files
committed
feat: added isValidUrl util
1 parent 34720de commit b57f44a

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,22 @@ console.log(isValidEmail(email1)); // true
7171
console.log(isValidEmail(email2)); // false
7272
```
7373

74+
### `isValidHttpUrl`
75+
76+
Validates if a given string is a valid URL
77+
78+
**Usage:**
79+
80+
```typescript
81+
import { isValidHttpUrl } from "largs-utils";
82+
83+
isValidHttpUrl("https://google.com"); // true
84+
isValidHttpUrl("http://example.com"); // true
85+
isValidHttpUrl("ftp://fileserver.com"); // false
86+
isValidHttpUrl("javascript:alert(1)"); // false
87+
isValidHttpUrl("random-string"); // false
88+
```
89+
7490
### `shuffleArray `
7591

7692
Randomly shuffles the elements of an array.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { isValidHttpUrl } from "../isValidHttpUrl";
2+
3+
describe("isValidHttpUrl", () => {
4+
it("should return true for valid http and https URLs", () => {
5+
expect(isValidHttpUrl("https://google.com")).toBe(true);
6+
expect(isValidHttpUrl("http://example.com")).toBe(true);
7+
});
8+
9+
it("should return false for non-http(s) URLs", () => {
10+
expect(isValidHttpUrl("ftp://fileserver.com")).toBe(false);
11+
expect(isValidHttpUrl("file:///Users/yourname/file.txt")).toBe(false);
12+
expect(isValidHttpUrl("javascript:alert(1)")).toBe(false);
13+
});
14+
15+
it("should return false for invalid URLs", () => {
16+
expect(isValidHttpUrl("not-a-link")).toBe(false);
17+
expect(isValidHttpUrl("random string")).toBe(false);
18+
expect(isValidHttpUrl("")).toBe(false);
19+
});
20+
21+
it("should return false for URLs missing protocol", () => {
22+
expect(isValidHttpUrl("www.google.com")).toBe(false);
23+
expect(isValidHttpUrl("google.com")).toBe(false);
24+
});
25+
});

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ export { camelToSentenceCase } from "./camelToSentenceCase";
22
export { coercedGet } from "./coercedGet";
33
export { generatePrefixedId } from "./generatePrefixedId";
44
export { isValidEmail } from "./isValidEmail";
5+
export { isValidHttpUrl } from "./isValidHttpUrl";
56
export { shuffleArray } from "./shuffleArray";
67
export { toKebabCase } from "./toKebabCase";

src/isValidHttpUrl.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export const isValidHttpUrl = (string: string) => {
2+
try {
3+
const url = new URL(string);
4+
return url.protocol === "http:" || url.protocol === "https:";
5+
} catch (_) {
6+
return false;
7+
}
8+
};

0 commit comments

Comments
 (0)