C# Form Validation Class
A nice little form validation class. It provides validation for Phone, Email, URL and Zipcode but its real easy to extend.
Code
public class FormValidator { public static IDictionary<string, Regex> RegexDictionary = new Dictionary<string, Regex>() { { "Phone", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")}, { "Email", new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+" + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$" )}, { "URL", new Regex(@"(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?")}, { "ZipCode", new Regex("^[0-9]{5}$")} }; public static bool IsPhoneValid(string phone) { return RegexDictionary["Phone"].IsMatch(phone); } public static bool IsEmailValid(string email) { return RegexDictionary["Email"].IsMatch(email); } public static bool IsURLValid(string url) { return RegexDictionary["URL"].IsMatch(url); } public static bool IsZipCodeValid(string url) { return RegexDictionary["ZipCode"].IsMatch(url); } } |
Use
if (String.IsNullOrEmpty(email) || !FormValidator.IsEmailValid(email)) // Do something email is required |




