SSW Foursquare

Do you use a regular expression to validate an URL?

Last updated by Brook Jeynes [SSW] 7 months 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.

We open source. Powered by GitHub