-
Notifications
You must be signed in to change notification settings - Fork 6
Enhancment/url validator harsh #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import { validateUrl } from "./url"; | ||
|
||
describe("url tests", () => { | ||
test.each([ | ||
["google.com", true], | ||
["https://www.example.com", true], | ||
["http://localhost:3000", true], | ||
["invalid_url", false], | ||
["javascript:alert('XSS')", false], | ||
["ftp://example.com", false], | ||
["mailto:[email protected]", false], | ||
["", false], | ||
[123, false], | ||
[null, false], | ||
[undefined, false], | ||
])('validateUrl("%s")', (value, expected) => { | ||
expect(validateUrl(value)).toBe(expected); | ||
}); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
/** | ||
* Validate the url | ||
* @param value The Url String | ||
* @returns The parsed boolean | ||
*/ | ||
export function validateUrl(value?: string | number | null): boolean { | ||
try { | ||
if (!value || typeof value !== "string") { | ||
return false; | ||
} | ||
|
||
if (!value.startsWith("http://") && !value.startsWith("https://")) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Limit to only consider "http/https" protocols might not be good for a And at this point it might be good to have both,
what you think? |
||
value = "http://".concat(value); | ||
} | ||
|
||
const urlPattern = /^(http|https):\/\/[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i; | ||
return urlPattern.test(value); | ||
} catch (err) { | ||
return false; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This check can be replaced with the
isNullOrEmpty
orisNullOrWhitespace
utility method.