Click here to Skip to main content
Licence CPOL
First Posted 14 Jun 2006
Views 32,222
Bookmarked 23 times

Regular Expression Validation Class

By | 14 Jun 2006 | Article
A class that allows easy validation of variables via Regular Expressions

Introduction

I often find myself re-writing the same bits of code for various projects. I know the whole point of object oriented design is to avoid this so I made myself this little Regex validation class. I find it useful for validating inputs and database values, etc. Hope you find it useful as well. Any pointers on how to extend it or better regular expressions will be gladly accepted.

The Code

using System;
using System.Collections;
using System.Text.RegularExpressions;
namespace Company.Validation
{
    public enum ValidationTypes
    {
	PositiveDecimal,
	Decimal,
	PositiveNonDecimal,
	NonDecimal,
	DatesDDMMYYYY,
	DatesDDMMYY,
	DatesDD_MMM_YYYY,
	Email,
	IPAddress,
	URL
    }

    /// <summary>
    /// To Validate strings against Regular Expression strings.
    /// </summary>
    public class RegExValidate
    {
        static ArrayList RegexStrings;
        static RegExValidate()
        {
            RegexStrings = new ArrayList();
	   //PositiveNumber
	   RegexStrings.Insert( (int)ValidationTypes.PositiveDecimal, 
		@"^[0-9][0-9]*(\.[0-9]*)?$");
	   //Number
	   RegexStrings.Insert( (int)ValidationTypes.Decimal, 
	  	@"^(\+|-)?[0-9][0-9]*(\.[0-9]*)?$");
	   //PositiveNonDecimal
	   RegexStrings.Insert( (int)ValidationTypes.PositiveNonDecimal, 
		@"^[0-9][0-9]*$");
	   //NonDecimal
	   RegexStrings.Insert( (int)ValidationTypes.NonDecimal, 
	 	@"^(\+|-)?[0-9][0-9]*(\.[0-9]*)?$");
	   //Dates(DD/MM/YYYY)
	   RegexStrings.Insert( (int)ValidationTypes.DatesDDMMYYYY, 
		@"((0[1-9]|[12][0-9]|3[01]))[/|-](0[1-9]|1[0-2])
		[/|-]((?:\d{4}|\d{2}))");
	   //Dates(DD/MM/YY)
	   RegexStrings.Insert( (int)ValidationTypes.DatesDDMMYY, 
		@"((0[1-9]|[12][0-9]|3[01]))[/|-](0[1-9]|1[0-2])[/|-]((?:\d{2}))");
	   //Dates(DD MMM YYYY)
	   RegexStrings.Insert( (int)ValidationTypes.DatesDD_MMM_YYYY, 
	 	@"^((31(?!\ (Feb(ruary)?|Apr(il)?|June?|
		(Sep(?=\b|t)t?|Nov)(ember)?)))|
	 	((30|29)(?!\ Feb(ruary)?))|(29(?=\ 
		Feb(ruary)?\ (((1[6-9]|[2-9]\d)(0[48]|
		[2468][048]|[13579][26])|((16|[2468][048]|
		[3579][26])00)))))|(0?[1-9])|1\d|2[0-8])\ 
		(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|
		Ju((ly?)|(ne?))|Aug(ust)?|
		Oct(ober)?|(Sep(?=\b|t)t?|Nov|Dec)(ember)?)\ 
		((1[6-9]|[2-9]\d)\d{2})");
	  //Email
	  RegexStrings.Insert( (int)ValidationTypes.Email, 
		@"([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})");
	  //IPAddress
	  RegexStrings.Insert( (int)ValidationTypes.IPAddress, 
	 	@"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>
		2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>
		2[0-4]\d|25[0-5]|[01]?\d\d?)\.
		(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)");
	  //URL
	  RegexStrings.Insert( (int)ValidationTypes.URL, 
		@"(?<protocol />\w+):\/\/(?<Domain>[\w.]+\/?)\S*");
        }
		
        /// <summary>
        /// Method returns true if unknown string matches the 
        /// regular expression defined by type
        /// </summary>
        /// <param name="type">ValidationTypes enum</param>
        /// <param name="unknown">String to validate</param>
        /// <returns>True if string validates</returns>
        public static bool Process(ValidationTypes type,string unknown)
        {
	   string test = RegexStrings[(int)type].ToString();
	   // Create a new Regex object.
	   Regex r = new Regex(RegexStrings[(int)type].ToString());
	   // Find a single match in the string.
	   Match m = r.Match(unknown);
	   return m.Success;
        }
    }
}

So it's used something like this.
You call the static method Process with the Validation Type you require and a string value of the object you are trying to validate.
This returns true if the string value is of that type and false if it's not.
For more stuff, see www.chemlock.co.uk.

History

  • 14th June, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Cheml0ck

Web Developer

United Kingdom United Kingdom

Member

Have been working with computers since the early 80's when our junior school got a BBC Micro. Every since then I've been building, fixing, configuring, installing, networking, coding and designing with them. At present I mainly code web applications in C#/ASP.NET. I'm very interested in Design Patterns and try and use these generic principles in all new projects to create truly n-tier architectures. You can keep up on current affairs on www.steelcurve.com


Ok so the pictures not of me, it's my little girl who makes coding everyday worth while. I just hope she becomes a lawyer not a developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pingroupsachin10d23:33 1 Nov '11  
Bugerror Pinmemberismailqadri2020:08 23 Jun '11  
GeneralNot Running Properly Pinmemberpankaj.indore17:40 6 Jun '07  
GeneralRegular Expression Class PinmemberbuyValu11:10 18 May '07  
GeneralSuggestion [modified] PinmemberSteve Hansen6:37 15 Jun '06  
GeneralRe: Suggestion PinmemberCheml0ck9:05 15 Jun '06  
GeneralRange Validator Pinmembercorrettore_automatico3:57 15 Jun '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 14 Jun 2006
Article Copyright 2006 by Cheml0ck
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid