Validating a Domain Using Regex
8/4/2009
This one is rather short, but basically I needed a regex string that could tell if what I was being fed was a web site or something else without actually going to said site. And really all I needed to check was that the data could possibly be a domain. That's it. So after looking at some of the more complex and most likely overkill examples out there, I decided to roll my own:
1: /// <summary>
2: /// Checks to see if a string is a valid domain
3: /// </summary>
4: /// <param name="Input">Input string</param>
5: /// <returns>True if it is a valid domain, false otherwise</returns>
6: public static bool IsValidDomain(string Input)
7: {
8: if (string.IsNullOrEmpty(Input))
9: return false;
10: Regex TempReg = new Regex(@"^(http|https|ftp)://([a-zA-Z0-9_-]*(?:\.[a-zA-Z0-9_-]*)+):?([0-9]+)?/?");
11: return TempReg.IsMatch(Input);
12: }
The code above simply looks for something starting with either http, https, or ftp and then the domain, and finally the port if it exists. I could even use this to separate out the various parts if need be (just sort out the various groupings). So it's simple, straightforward, and probably a bit buggy, but it's been working on my test data which is enough for now. So try it out, leave feedback, and happy coding.