| 1 |
// URL validation utility |
| 2 |
|
| 3 |
/** |
| 4 |
* Checks if a string is a valid URL for the form builder. |
| 5 |
* Allows domains, localhost, IPv4, IPv6, with optional port and path. |
| 6 |
* Disallows multiple protocols and garbage before the URL. |
| 7 |
*/ |
| 8 |
export function isValidUrl(urlInput: string): boolean { |
| 9 |
if (!urlInput) return false |
| 10 |
const url = urlInput.trim() |
| 11 |
// Allow domains, localhost, IPv4, IPv6 |
| 12 |
const startPattern = |
| 13 |
/^(https?:\/\/)?([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*|localhost|\d{1,3}(\.\d{1,3}){3}|\[[0-9a-fA-F:]+\])(:\d+)?(\/|$)/ |
| 14 |
if (!startPattern.test(url)) return false |
| 15 |
// Disallow protocol more than once |
| 16 |
const protocolMatches = url.match(/https?:\/\//gi) |
| 17 |
if (protocolMatches && protocolMatches.length > 1) return false |
| 18 |
// Use URL constructor for validation |
| 19 |
let urlToTest = url |
| 20 |
try { |
| 21 |
if (!/^https?:\/\//i.test(url)) { |
| 22 |
urlToTest = 'https://' + url |
| 23 |
} |
| 24 |
new URL(urlToTest) |
| 25 |
return true |
| 26 |
} catch { |
| 27 |
return false |
| 28 |
} |
| 29 |
} |
| 30 |
|