A helper method to validate if a URL is valid
public static class UrlValidation
{
public static bool IsValidUrl(string value)
{
StringValidation.IsRequired(value, "Validation.IsUrl's value can't be null or empty");
string strRegex = "^(https?://)" +
"?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" + //user@
@"(([0-9]{1,3}\.){3}[0-9]{1,3}" + // IP- 199.194.52.184
"|" + // allows either IP or domain
@"([0-9a-z_!~*'()-]+\.)*" + // tertiary domain(s)- www.
@"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." + // second level domain
"[a-z]{2,6})" + // first level domain- .com or .museum
"(:[0-9]{1,4})?" + // port number- :80
"((/?)|" + // a slash isn't required if there is no file name
"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
Regex re = new Regex(strRegex);
return re.IsMatch(value);
}
}
Fork
0 Feedback
You must log in before you can give any feedback
0
The problem with using Regex is that you are essentially embedding another language into a string object. This means that you won't get any usable feedback of any errors in that string/language. So in my mind this should only be used when there is no other option.
Therefor I would prefere the existing Uri.IsWellFormedUriString method when possible.
You must log in before you can post a comment


832
0


Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'