Home
Do you use a regular expression to validate an URL?
  v1.0 Posted at 27/04/2018 3:33 AM by Tiago Araujo
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.​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.