 
    Validations using regular expressions and commonly used regex validations
    
    
    
Validating input using .net regular expression validation control 
  
 <asp:RegularExpressionValidator ID="rgexpval" runat="server" ControlToValidate="txtMinAmt" ErrorMessage="Please Provide a Valid Numeric Value." ValidationExpression="^[-]?\d+(\.\d+)?$" 
 ValidationGroup="GrpS3PL" Visible="False">* </asp:RegularExpressionValidator> 
 
 Above control checks if the textbox txtMinAmt contains numeric values. 
 ValidationExpression contains the regular repression to validate textbox txtMinAmt for numeric values 
 Regular expression validation can be done through code behind as well 
 if (System.Text.RegularExpressions.Regex.IsMatch(txtMinAmt.Text, @"^[-]?\d+(\.\d+)?$")) 
             {
                // email is valid
                // ...
            } 
 Regex  ismatch function return either true or false as result. 
  
  
 
 Short introduction on regular expressions 
  
 Below are some of the sample Regular expressions commonly used for validations in practical scenarios: 
  
 Regex for valid Email Id  
 Pattern: 
 /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/   
 Description: 
 Parser first find the beginning of the string (^).  
 Inside the first group, one or more lowercase letters, dots, numbers, hyphens, or underscores is matched.  
 After first group match, we check for @ sign. 
 Next is the domain name which must be: one or more lowercase letters, underscores, numbers, dots, or hyphens.  
 Then comes the (escaped) dot, followed by the extension being two to six letters or dots. 2 to 6 because of the country specific TLD’s (.ny.us or .co.uk). Finally, we want the end of the string ($).  
 String that matches: 
 [email protected] 
 String that doesn’t match: 
 [email protected] (TLD is too long) 
  
 Regex for checking valid Url 
 Pattern:
 /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/   
 Description: 
 Firstly, it checks if the URL starts with “https://”, “https://”, or neither of them. Question mark after the s allows URL’s to have either http or https. Typing HTTP or HTTPS can be optional as well. So a question mark is added at the end of it.  
 Next is the domain name which can be one or more numbers, letters, dots, or hypens followed by another dot then two to six letters or dots. Inside the group, we want to match any number of forward slashes, underscores, numbers, spaces, letters, dots, or hyphens. In this case, star is used instead of the question mark because the star says zero or more, not zero or one. If a question mark has to be used there, only one file/directory would have been matched.  
  
 Regex for checking IP Address Pattern 
 Pattern:
 \b (((\d{1, 2})| ([0-1]\d {2})| (2[0-4]\d)| (25[0-5]))\.){3}((\d{1, 2})| ([0-1]\d {2})| (2[0-4]\d)| (25[0-5]))\b  
 Description: 
 2} check for numbers between 0 and 99  
 [0-1]\d{2} allows numbers between 100 and 199 in the form 0nn 
 2[0-4]\d permits numbers between 200 and 249 
 25[0-5] check for numbers from 250 to 255 
 Above four patterns are combined into an alternation and a \ is appended every time to enforce a. after every 2 or 3 digit number. 
 {3} means three sets of numbers like - nn. Or nnn to be provided. 
 Pattern 0-99, 100-199/0nn, 200-249 and 250-255 are repeated one more time to test for the final two/three digit number. 
 Wrap the pattern in word boundary constraints \b to ensure that the first & fourth block of two/three digit numbers are not preceded/followed by an illegal character. 
  
 Regex for checking Credit Card Pattern 
 Pattern:
 ((4\d {3})| (5[1-5]\d {2})| (6011))(|)? \d {4} (\5\d{4}){2} 
 Description: 
 4d {3} - checks if the Visa card number always starts with the digit 4. 
 5[1-5] d {2} - check for Mastercard numbers which start with 51-55. 
 6011 - Permits Discover numbers which always start with 6011. 
 Above three patterns are combined into an alternation 
 (|)? \d{4} - requires a set of four digits optionally preceded by a space. 
 (\5\d{4}){2} - requires two more sets of four digits preceded by a space 
   is a back reference - back references in regexes are simply numbered from left to right, irrespective of any nesting of the individual patterns. 
 Note that this pattern validator does not necessarily ensure that the number provided matches a real credit card. Credit card numbers contain an issuer identifier and a final check digit which must be valid.  
  
 Regex for checking US Telephone Number Pattern 
 Pattern:
 (? [2-9]\d\d\)? (-| |\.)[2-9]\d\d\1\d{4} 
Description: 
 The number is represented as three blocks of digits separated by a space a hyphen or a dot. 
 Separator characters cannot mix. I.e. (574) 975 1571 is legal but (574) 975.1571 is not. 
 The number is prefixed with three digits. First digit cannot be 0 or 1. 
 The prefix may be placed in parentheses. 
 The second block of digits consists of three numbers with first digit never being 0 or 1. 
 The final block is made up of any four digits. 
 We instruct the regex engine to index the first separator character for back referencing by using the code ([\.-]). At the location of the second separator character we use the back reference code . This ensures that numbers with mixed separator characters are not accepted. 
 This pattern will quite happily accept numbers bearing the form (574.975.1571 or 574) 975 1571.  
 
 Similarly, below are some of the remaining validation done using regular expressions 
 Regex for checking valid IP Address 
 Pattern: 
 /^(?:(?: 25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/   
 String that matches: 
 73.60.124.136 (no, that is not my IP address: P) 
  
 Regex for checking valid HTML 
 Pattern: 
 /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/   
 String that matches: 
 <a href=”https://net.tutsplus.com/”>Nettuts+</a> 
 String that doesn’t match: 
 <img src=”img.jpg” alt=”My image>” /> (attributes can’t contain greater than signs) 
  
 
 Regex for checking indian pin code of six digits 
 Pattern: 
 [0-9]{6}
 String that matches: 
 400604 
 String that doesn’t match: 
 Any numeric value not consisting of six digits Ex: 40050 or 4000504 
  
 Regex for checking date in the European format of dd/mm/yyyy 
 Pattern: 
 ^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$  
 String that matches: 
 07/06/1985 
 String that doesn’t match: 
 12/29/2007 
 
 Regex for checking date between 1-1-1757 to 31-12-9999 
 Pattern: 
 (0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-]((175[7-9])|(17[6-9][0-9])|(1[8-9][0-9][0-9])|([2-9][0-9][0-9][0-9])) 
 String that matches: 
 07-06-1985 
 String that doesn’t match: 
 12-29-2007 
 
 Regex for checking date between 1-1-1757 to 31-12-9999 
 Pattern:  
(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-]((175[7-9])|(17[6-9][0-9])|(1[8-9][0-9][0-9])|([2-9][0-9][0-9][0-9])) 
 String that matches: 
 07-06-1985 
 String that doesn’t match: 
 12-29-2007 
  
 Regex for checking time in format hh:mm:ss AM/PM 
 Pattern: 
 (0[1-9]|[1][0-2])[:](0[0-9]|[1-5][0-9])[:](0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]
 String that matches: 
 12:20:50 PM 
 String that doesn’t match: 
 12:70:50 PM 
  
 Regex for checking numeric value 
 Pattern: 
 [0-9]* 
 String that matches: 
 5465131265 
 String that doesn’t match: 
 5345fh2454 
  
 Regex for checking non-numeric value 
 Pattern: 
 [+]?[0-9]*\\.?[0-9]* 
 String that matches: 
 5465131265 
 String that doesn’t match: 
 -53452454 
  
 Regex for checking Social Security Number Pattern 
 Pattern:
 -\d{2}-\d{4} 
 
 here
 here
 
    
    
        Note: Images used on this website
        are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon
        Foundation or were found in google search under "Free to use and share". If any
        of the images presented here violates copyright issues or infringes anyone copyright
        or are not under "Fair use", then please bring it to our notice. Read 
Disclaimer for more.
    
 
    
    
        Share this to your friends. One of your friend is
        waiting for your share.
    
    
    Related Articles 
    
            Displaying Image in silverlight Datagrid
        
            Visitors-Hits counter for your website
        
            Tips and tricks with ajax calendar extender control
        
            Data Validation using Ajax MaskedEditExtender control
        
            Validations using regular expressions and commonly used regex validations
        
            Populating RSS XML Feed or XML data on Datagrid
        
            Advanced Datetime Format for string
        
            Different Strings Format for Date Time
        
    
    Post Comment