Created
January 11, 2023 10:56
-
-
Save smdooley/1752027ae8422fb592a757a8b1a0fd3d to your computer and use it in GitHub Desktop.
UrlHelper class to validate URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text.RegularExpressions; | |
using Umbraco.Extensions; | |
namespace Concept.Core.Helpers | |
{ | |
public static class UrlHelper | |
{ | |
private const string URL_SCHEME_PATTERN = @"^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"; | |
private const string URL_RELATIVE_PATTERN = @"^\/([\w-]+.)+[\w-]+(\/[\w- ])?\S$"; | |
public static string GetCorrectUrl(string url) | |
{ | |
try | |
{ | |
string sanitisedUrl = SanitiseUrl(url); | |
if (IsValidUrl(sanitisedUrl)) return sanitisedUrl; | |
return "#"; | |
} | |
catch | |
{ | |
return "#"; | |
} | |
} | |
public static bool IsValidUrl(string url) | |
{ | |
try | |
{ | |
Uri uriResult; | |
Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uriResult); | |
if (uriResult is null) return false; | |
if (uriResult.IsAbsoluteUri) return true; | |
if (Regex.IsMatch(uriResult.OriginalString, URL_SCHEME_PATTERN)) return true; | |
if (Regex.IsMatch(uriResult.OriginalString, URL_RELATIVE_PATTERN)) return true; | |
return false; | |
} | |
catch | |
{ | |
return false; | |
} | |
} | |
public static string SanitiseUrl(string url) | |
{ | |
if (string.IsNullOrWhiteSpace(url)) return "#"; | |
if (url.StartsWith("http:") || url.StartsWith("https:") || url.StartsWith("mailto:") || url.StartsWith("tel:")) | |
{ | |
return url; | |
} | |
if (url.StartsWith("//")) | |
{ | |
return $"http:{url}"; | |
} | |
if (url.StartsWith("www.")) | |
{ | |
return $"http://{url}"; | |
} | |
if (Regex.IsMatch(url.ReplaceFirst("/", ""), URL_SCHEME_PATTERN)) | |
{ | |
return $"http://{url.ReplaceFirst("/", "")}"; | |
} | |
if (!url.StartsWith("/")) | |
{ | |
url = $"/{url}"; | |
} | |
if (Regex.IsMatch(url, URL_RELATIVE_PATTERN)) | |
{ | |
return url; | |
} | |
return "#"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment