In one of the project i am working at, i need to validate a url, an email and ip address. I googled so many regular expressions, and almost %99 of the ones i found had some issues :). I collected the working one, in an extension class, so that i can use extensions to validate now. Here is the class i have:
public static class Validations {
public static bool IsValidEmail(this string Email)
{
if (String.IsNullOrEmpty(Email))
return false;
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}"+
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(Email))
return (true);
return (false);
}
public static bool IsValidIPAddress(this string IP)
{
if(String.IsNullOrEmpty(IP))
return false;
IPAddress ipAddress;
bool valid = IPAddress.TryParse(IP, out ipAddress);
return valid;
}
public static bool IsValidUrl(this string Url)
{
if(String.IsNullOrEmpty(Url))
return false;
string strRegEx = @"^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)"+
@"?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*"+
@"(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$";
Regex re = new Regex(strRegEx);
if(re.IsMatch(Url))
return true;
return false;
}
}
Have fun :)