Regular expressions are often used for user input validation. One common problem is to validate that the e-mail that the user entered is valid. There are a zillion readymade e-mail regex for your use, but I was always interested in knowing why something works, so I set about to create my own regex. That led to my making more commonly-used regular expressions, so I thought I’d share them.

Note that I’m still very much of a newbie when it comes to regular expressions, so these might not be the most efficient ways to validate the appropriate inputs. I checked that each pattern’s working using RadSoftware’s excellent RegexDesigner. It’s such a relief to not have to not have to write a test application.

Oh, the “#” you see in the regular expressions are comments.

  1. using System;
  2. using System.Text.RegularExpressions;
  3. namespace SG.Net.Utilities
  4. {
  5. public class InputValidation
  6. {
  7. /// <summary>
  8. /// A password is valid if
  9. /// 1. It’s at least [minLength] long.
  10. /// 2. It has at least one uppercase letter.
  11. /// 3. It has at least one lowercase letter.
  12. /// 4. It has at least one digit.
  13. /// 5. It has at least one non-alphanumeric character.
  14. /// </summary>
  15. /// <param name="password">The password to validate.</param>
  16. /// <param name="minLength">Minimum length of the password.</param>
  17. /// <returns>True if the password is valid, false otherwise.</returns>
  18. public static bool ValidatePassword(string password, int minLength)
  19. {
  20. Regex pattern = new Regex(@"
  21. ^ # Match the start of string
  22. (?=.*d) # Do we have at least one digit?
  23. (?=.*[A-Z]) # Do we have at least one uppercase letter?
  24. (?=.*[a-z]) # Do we have at least one lowercase letter?
  25. (?=.*[^a-zA-Z0-9nrt ]) # Do we have at least one non-alphanumeric character?
  26. .{" + minLength.ToString() + @",} # Is it at least 6 characters long?
  27. $ # Match the end of the string
  28. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
  29. return pattern.IsMatch(password);
  30. }
  31. /// <summary>
  32. /// An email is valid if
  33. /// 1. It contains an ‘@’ symbol.
  34. /// 2. It contains a ‘.’ symbol.
  35. /// 3. There are alphanumeric characters (or certain symbols) in front of the ‘@’ symbol.
  36. /// 4. There are alphanumeric characters in between ‘@’ and ‘.’ symbols.
  37. /// 5. There are alpha characters after the ‘.’ symbol.
  38. /// </summary>
  39. /// <param name="email">The email address to validate.</param>
  40. /// <returns>True if email is valid, false otherwise.</returns>
  41. /// <remarks>
  42. /// This function supports multiple subdomains.
  43. /// Check http://www.ietf.org/rfc/rfc2822.txt for generic syntax of emails
  44. /// </remarks>
  45. public static bool ValidateEmail(string email)
  46. {
  47. Regex pattern = new Regex(@"
  48. ^ # Match the beginning of the string
  49. [a-zA-Z0-9]+ # Start with an alphanumeric character
  50. [a-zA-Z0-9!`#$^&*]* # Allow for any number of approved symbols
  51. @ # Match the ‘@’ symbol
  52. [a-zA-Z0-9]+ # One or more alphanumeric characters
  53. [a-zA-Z0-9.]* # Allow for subdomains
  54. . # Match the ‘.’ symbol
  55. [a-zA-Z]+ # Match the domain
  56. $ # Match the end of the string
  57. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
  58. return pattern.IsMatch(email);
  59. }
  60. /// <summary>
  61. /// A social security number is valid if it’s 9 digits long.
  62. /// </summary>
  63. /// <param name="ssn">The social security number to validate.</param>
  64. /// <returns>True if the ssn is valid, false otherwise. </returns>
  65. public static bool ValidateSSN(string ssn)
  66. {
  67. //Strip the seperators (for example, ‘-’). It’s so much easier to code the regular
  68. //expression when we don’t have to handle the seperators (which the user may or may
  69. //not have entered.
  70. ssn.Trim().Replace("-", String.Empty).Replace(".", String.Empty).Replace(" ", String.Empty);
  71. return Regex.IsMatch(ssn, @"^d{9}$");
  72. }
  73. /// <summary>
  74. /// A phone number is valid if it is 6 or 9 digits long.
  75. /// </summary>
  76. /// <param name="phoneNumber">The phone number to validate.</param>
  77. /// <returns>True if phone number is valid, false otherwise.</returns>
  78. /// <remarks>Obviously, this doesn’t allow for international phone numbers.</remarks>
  79. public static bool ValidatePhoneNumber(string phoneNumber)
  80. {
  81. //Valid phone numbers, for example, include:
  82. //1. (999)-999-9999
  83. //2. (999)999-9999
  84. //3. 999-999-9999
  85. //4. 9999999999
  86. //So we’ll once again strip the seperators to make our lives easier.
  87. //(), ‘-’, ‘.’, and ‘ ‘ are considered valid seperators.
  88. phoneNumber.Trim().Replace("(", String.Empty).Replace(")", String.Empty).
  89. Replace("-", String.Empty).Replace(".", String.Empty).
  90. Replace(" ", String.Empty);
  91. return ((Regex.IsMatch(phoneNumber, @"^d{9}$") || Regex.IsMatch(phoneNumber, @"^d{6}$")));
  92. }
  93. /// <summary>
  94. /// Validates a date using C#-built in DateTime.TryParse()
  95. /// function.
  96. /// </summary>
  97. /// <param name="date">The date to validate</param>
  98. /// <returns>True if the date is valid, false otherwise.</returns>
  99. public static bool ValidateDate(string date)
  100. {
  101. //Dates can be entered in a couple of different formats:
  102. //1. 2006-03-04
  103. //2. 03-04-2006
  104. //3. April 3 2006
  105. //4. April 3, 2006
  106. //5. Apr 3, 2006
  107. //6. 03-APR-2006
  108. //7. 3-APR-06
  109. //You get the idea.
  110. //It’s probably doable with regular expressions, but we
  111. //might as well use C#’s awesome DateTime.Parse(string date)
  112. //method to validate the date.
  113. DateTime dateParsed = new DateTime();
  114. return DateTime.TryParse(date, out dateParsed);
  115. }
  116. /// <summary>
  117. /// An IP Address is valid if it’s 10 digits long.
  118. /// </summary>
  119. /// <param name="ipaddress">The IP Address to validate</param>
  120. /// <returns>True if IP Address is valid, false otherwise.</returns>
  121. public static bool ValidateIPAddress(string ipaddress)
  122. {
  123. //We’re only going to allow the ‘.’ for a seperator.
  124. ipaddress.Trim().Replace(".", String.Empty);
  125. //We’ll also strip the ‘http://’, ‘https://’, or ‘ftp://’
  126. ipaddress.Replace("http://", String.Empty).Replace("https://", String.Empty).
  127. Replace("ftp://", String.Empty);
  128. return Regex.IsMatch(ipaddress, @"^d{10}$");
  129. }
  130. /// <summary>
  131. /// Validates most forms of urls.
  132. /// </summary>
  133. /// <param name="url">The URL to validate</param>
  134. /// <returns>True if the URL is valid, false otherwise.</returns>
  135. /// <remarks>Check http://www.ietf.org/rfc/rfc2396.txt for generic syntax of URLs.</remarks>
  136. public static bool ValidateURL(string url)
  137. {
  138. //Valid urls include:
  139. //1. http://www.awesomesite.com/
  140. //2. http://awesomesite.com/
  141. //3. www.awesomesite.com
  142. //4. www.awesomesubdomain.awesomesite.com
  143. //5. http://www.awesomesite.com/awesomepage.aspx
  144. //6. ftp://awesomesite.com
  145. //7. 999.999.999 (IP Address)
  146. //8. https://awesomesite.com/
  147. //9. awesomesite.com
  148. //10. http://999.999.999
  149. //Substitute whatever domain name you want for the ‘com’
  150. //We’ll check for the domain case first, and the ip address case
  151. //second.
  152. Regex pattern = new Regex(@"
  153. ^ # Match start of string
  154. ( # Match one of
  155. ftp://| # these
  156. https://| # three
  157. http:// # characters
  158. )? # (optional); followed
  159. (www.)? # optionally by the string ‘www.’ followed by
  160. [A-Za-z0-9]+ # one or more alphanumeric characters
  161. [A-Za-z0-9.]* # Allow for subdomains
  162. . # Match the ‘.’ symbol
  163. [A-Za-z]+ # Followed by one or more alphanumeric characters
  164. /? # Followed by an optional (closing) slash
  165. (
  166. /[A-Za-z0-9/]+ # Allow for pages
  167. . # Match the ‘.’ symbol
  168. [A-Za-z0-9/]+ # Match the page’s extension
  169. )? # All of which is optional, of course
  170. $ # Match end of string
  171. ", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
  172. if(pattern.IsMatch(url))
  173. return true;
  174. //Let’s now try to check for the IP Address case
  175. return InputValidation.ValidateIPAddress(url);
  176. }
  177. }
  178. }