Do you use a regular expression to validate an URL?

Last updated by Brook Jeynes [SSW] over 1 year ago.See history

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: 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: Good example of verifying URI

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

Adam Cogan
We open source.Loving SSW Rules? Star us on GitHub. Star
Stand by... we're migrating this site to TinaCMS