Do you use a regular expression to validate an URL?
Updated by Brook Jeynes [SSW] 2 years ago. See history
123
<introEmbed
body={<>
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.
Related rules
Need help?
SSW Consulting has over 30 years of experience developing awesome software solutions.