Regular expressions are patterns used to match character combinations in strings.
You can use the regular expression to valid an email format, url, zipcode, phone number, alpha numeric, area code...etc
I'll create an extension of the string class that allows you to check the validity of an email address
public static class StringExtensions
{
static readonly Regex EmailExpression = new Regex(@"^([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})(\]?)$", RegexOptions.Compiled | RegexOptions.Singleline);
public static bool IsEmail(this string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
else
{
return EmailExpression.IsMatch(s);
}
}
}
or simple
public static bool IsValidEmailAddress(string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
Validates the zip code
public bool ValidateZipCode(string zipCode)
{
if (string.IsNullOrEmpty(zipCode))
return false;
return Regex.IsMatch(zipCode, "(^[0-9]{5}$)|(^[0-9]{5}-[0-9]{4}$)");
}
Validates Url
public bool IsValidUrl(string url)
{
Regex rx = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.Compiled);
return rx.IsMatch(url);
}
Validates alpha numeric
public bool IsAlphaNumeric(string value)
{
return Regex.IsMatch(value, "^[a-zA-Z0-9]*$");
}
Validates the phone number
/// <summary>
/// Validates the phone number
/// '222-113-2567', '(222)123-4567', '2221234567', '(222) 123-4567', '(222)-123-1569'
/// </summary>
/// <param name="phoneNumber">Phone number</param>
/// <returns>True if phone number is valid</returns>
public static ValidatePhoneNumber(string phoneNumber)
{
if (String.IsNullOrEmpty(phoneNumber))
return false;
return Regex.IsMatch(phoneNumber, "^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$");
}
Validates the area code
public bool ValidateAreaCode(string areaCode)
{
if (String.IsNullOrEmpty(areaCode))
return false;
return Regex.IsMatch(areaCode, "^[^01][0-9]{2}$");
}
Validates street address
public bool IsValidStreetAddress(string address)
{
string exp = @"\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}\s[a-zA-Z]{2,15}";
var regex = new Regex(exp);
return regex.IsMatch(address);
}