Do you use a regular expression to validate an URL?

Updated by Brook Jeynes [SSW] 1 year ago. See history

123

A regex is the best way to verify an URI.

public bool IsValidUri(string uri)
{
try
{
Uri testUri = new Uri(uri);
return true;
}
catch (UriFormatException ex)
{
return false;
}
}

❌ Figure: Figure: Bad example of verifying URI

public bool IsValidUri(string uri)
{
// Return true if it is in valid Uri format.
return System.Text.RegularExpressions.Regex.IsMatch( uri,@"^(http|ftp|https)://([^\/][\w-/:]+\.?)+([\w- ./?/:/;/\%&=]+)?(/[\w- ./?/:/;/\%&=]*)?");
}

✅ Figure: Figure: Good example of verifying URI

You should have unit tests for it, see our Rules to Better Unit Tests for more information.

acknowledgements
related rules