Applications Services Blog
Get the latest thought leadership and information about the role of Applications Services in an increasingly interconnected world at the HP Blog Hub.

Using regular expressions in Dynamics CRM 2011 processes

Regular expressions offer programmers an easy way to validate strings in many programming languages. In this post, I will show how you can add regular expression validation capabilities to Dynamics CRM 2011 processes.


Regular expressions overview

First, for those who may not be familiar with regular expressions, let me offer a brief example of what kinds of problems they can solve. Let's say you need to validate a U.S. or Canadian phone number in C#. These numbers are governed by the North American Numbering Plan (NANP) and can be formatted as 1-###-###-####. Because all of the countries in the NANP share the same 1 "country code," that is typically omitted from phone numbers when they are stored in a database for domestic use. If you use the string methods in C#, a basic validation function might look something like this:


bool ValPhoneNumber(string numberToValidate)
	//NANP phone numbers should be entered in this format 334-867-5309

	//create an array of the three sets of digits
	string[] phoneParts = numberToValidate.Split("-".ToCharArray());

	//if we have more or less than three sets, return false
	if (phoneParts.Length != 3)
		return false;
		//if the sets aren't the correct length, return false
		if ((phoneParts[0].Length != 3) || (phoneParts[1].Length != 3) || (phoneParts[2].Length != 4))
			return false;
			//if any of the sets can't be parsed as an integer, return false
			for (int i = 0; i < 3; i++)
				int parseResult;
				if (!Int32.TryParse(phoneParts[i], out parseResult))
					return false;


	//if we got here after all our previous checks, return true
	return true;

You'll note that code is extremely brittle. U.S. phone numbers are also sometimes represented in the form of (###) ###-#### or ###.###.####. To change to one of those formats from ###-###-#### or to add them as alternative options would be a non-trivial exercise.


On the other hand, if we use C#'s regular expression engine, which is found in the System.Text.RegularExpressions namespace, we can reduce the validation code to: 


bool ValPhoneNumber(string numberToValidate)
	//define the pattern
	string matchPattern = "^[2-9]\d{2}-d{4}-d{4}$";
	//do the match
	Match match = Regex.Match(numberToValidate, matchPattern, RegexOptions.IgnoreCase);
	//return the status of the match (true or false)
	return match.Success;

In this method, we define a pattern and then we run the regular expression engine against the supplied string input using the pattern. This is a relatively simple pattern to match all strings in the format of ###-###-#### that start with a number other than 1 or 0, which are invalid starting digits for NANP numbers. If we want to handle additional phone number patterns, we can add them to the match pattern using a regular expression OR operator. For example, "dog|cat" matches either "dog" or "cat." For more information on regular expressions in C#, I suggest you take a look at the MSDN .Net regular expression article here.


Regular expression uses in Microsoft Dynamics CRM

Now that you understand what regular expressions can do, take a minute to consider how you could use them to enhance the functionality of Dynamics CRM workflows and dialogs. Here are a couple of simple ideas, but I'll bet you can come up with plenty that are applicable to your own situation:

  1. When certain types of contacts are created, a workflow adds them to a marketing list. Use a regular expression to verify phone numbers are valid before contacts are added.
  2. Use a regular expression validator to scan the text of e-mails when they enter a particular queue. If the pattern matches, create a case tied to the e-mail.

 The bad news is that there's no out-of-the-box support for regular expressions in Dynamics CRM 2011 processes, so you'll have to roll your own custom workflow activity to handle it. The good news is that it's easy, and I can show you how in just a few lines of code.


The code

The custom workflow activity should do the following:

  1. Accept a string to validate and a regular expression match pattern via input arguments. Strictly speaking, you could hardcode the match pattern, but using an input argument gives you maximum flexibility.
  2. Evaluate the regular expression.
  3. Return the result of the match via an output argument.

Specifically, there are only two things we need to do. First we need to set up our input and output parameters:


[Input("String to validate")]
public InArgument<String> StringToValidate { get; set; }

[Input("Match pattern")]
public InArgument<String> MatchPattern { get; set; }

public OutArgument<int> Valid { get; set; }

You'll note that the Valid output parameter is an integer instead of a boolean. I decided to use 0 for false and 1 for true because CRM 2011 dialogs do not support boolean variables in the process definition. This way I can declare a variable up front and then set it to the validator activity's output.


Next, we add the following lines to our Execute method to actually evaluate the input string and the supplied regular expression:


//do the match
Match match = Regex.Match(StringToValidate.Get(executionContext), MatchPattern.Get(executionContext),RegexOptions.IgnoreCase);

//did we match anything?
if (match.Success)
	Valid.Set(executionContext, 1);
	Valid.Set(executionContext, 0);

You can download the complete custom workflow activity class file at the end of this post ( When I register the assembly in my CRM instance, I am then able to set up validation in a dialog like in the following screenshot:




How do you handle advanced validations in your Dynamics CRM processes? Can you think of some other interesting uses for regular expressions? Let us know in the comments!




Leave a Comment

We encourage you to share your comments on this post. Comments are moderated and will be reviewed
and posted as promptly as possible during regular business hours

To ensure your comment is published, be sure to follow the community guidelines.

Be sure to enter a unique name. You can't reuse a name that's already in use.
Be sure to enter a unique email address. You can't reuse an email address that's already in use.
Type the characters you see in the picture above.Type the words you hear.
About the Author
Microsoft Dynamics CRM solution architect, C# developer, MBA, husband, father, Auburn man. Follow me on Twitter @lucas_is.
About the Author(s)
  • Business Development leader for HP’s Testing Practice in Americas and TaaS Global Capability Leader
  • Anthony works in the ES Apps Enterprise APJ . He is a self-motivated and well-disposed individual. He is a certified SAP FICO consultant. He has over twenty years industry experience in business transformation and Information Technology consulting (SAP). With excellent, interpersonal and communication skills, Anthony is able to influence and motivate at all levels. An empathic team player, He derives fulfilment in contributing towards others' development. Anthony possesses good analytical and problem-solving skills. He is a quick thinker, remains calm under pressure, handles multiple tasks, and accomplishes objectives with excellent time management. He is flexible and accustomed to meeting high standards and deadlines. Anthony possesses practical knowledge of business processes and concepts and has a keen eye for detail. He is aware of the importance of an effective system and quality management.
  • Bryan Coapstick is the Director of Mobile Innovation at HP. In this role, he is responsible for driving strategic mobility initiatives and key industry partnerships to enable clients the ability to leverage the mobile channel to effectively reach their customers. Bryan’s expertise lies with several Fortune 200 companies in both public and private sectors that focus on business technology and emerging strategies. Bryan demonstrates innovative leadership though public speaking, panel discussions and blogging on the various ways mobility is changing our daily lives.
  • Benjamin Romberg has over twenty five years experience in the IT industry, the last twelve of which have been as a testing professional. He has experience as a test analyst, performance tester, automation specialist, test lead, test manager, test consultant and test executive. He has worked on all types of testing engagements ranging from small web based applications through to core system upgrades. Benjamin holds a Bachelor’s Degree in Genetics, a Post Graduate Degree in Software Engineering and an Executive Masters in Business Administration. Benjamin now leads HP’s Testing and Quality Assurance Practice in Asia Pacific and Japan.
  • Over the past 5 years, I have participated in the different stages of delivering Microsoft Enterprise Applications to customers as large as 40.000 concurrent users across Europe with a focus on the public and call center sector. During this period, I worked in numerous technical (lead) and business consultant roles. Using this experience, I am currently a certified Microsoft Dynamics CRM 2011 expert which specializes in guiding enterprise customers and implementation teams through the process of implementing Microsoft Dynamics CRM 2011.
  • Craig has been with HP for 10 years working on the solutioning side as a Solution Architect. Primarily works with Microsoft technologies and has for the better part of 16 years. This past year Craig has worked mostly with Windows AZURE and the mobility side of Windows Phone 7/8 and Android.
  • Master Business Consultant and Distinguished SE with 35+ years of IT experience, specializing in SOA and Integration.
  • Daniel Amor (EMEA, AMOD, Cloud, Portals, Web Apps and SOA domain expert): Daniel has designed, won, led and delivered large-scale, complex applications-related projects by acting as a trusted advisor to clients. Daniel conducts regular training and client-facing sessions, and he has authored six books and numerous articles in European and US-based magazines and newspapers on IT change. He is a regular lecturer and he speaks on Portals, E-Business and Cloud.
  • Global HP Microsoft Business Applications Practice. Microsoft Dynamics CRM subject matter expert. Based in Manchester, United Kingdom. @DarrenCRM on Twitter
  • Solutions Architect working at HP since 2002 with focus on Applications Modernization, located at Rio de Janeiro, Brazil
  • Managing Consulting specialising in Business Transformation and Value Management for Defence, Healthcare, Public Sector, Criminal Justice and Telecommunications.
  • Guido Arndt is since May 1997 business consultant and project manager @ Hewlett Packard Enterprise Services. Main focus is strategic and organizational alignment of logistics, sales and production processes in the automotive and manufacturing industry as well as business performance projects in finance and telecommunication industry. Guido has experience as change agent and transformation manager in people-driven merger & aquisition projects focusing government, consulting firms, manufacturing plants and consumer brands.
  • Horia Slușanschi serves as an Agile Coach leading the HP Agile Mentoring Office and the HP Software Engineering Profession. He is passionate about helping teams and leaders to find joy in work in the pursuit of customer delight.
  • CISSP, Open CA Master Architect Technical Consultant with 28+ years of IT experience specializing in Application Security, Solution Architecture, Portals, Social Business, and Integration
  • Jim has been with HP for 33 years and currently leads a global Strategic Capabilities Management team, with a specific focus on Business Analysis and Configuration Management. Jim also manages a team within the US State, Local, and Education division of HP. He was a member of the IIBA committee that created a Business Analyst Competency Model and he participated in the development of IEEE standards. Jim graduated from Harvard University, the University of British Columbia, and Ottawa Theological Hall. He currently lives in Toronto, Canada.
  • SAP Technologist from APPS GD SAP Practice - Manila covering SAP NetWeaver EP, SAP Mobility and general SAP solutions.
  • WW product marketing manager for HP Applications Modernization and Transformation Consulting Services. 35+ years of IT technology and services experience.
  • Laurence has over 35 years experience in the IT industry and has spent 27 years delivering knowledge management (and before that became fashionable, Artificial Intelligence and knowledge-based systems) transformation projects to clients in Government, Industry, Manufacturing and Telecomms industries. He has developed and implemented knowledge management (KM) strategies for HP's clients and for business areas in HP (for BPO and for our Consulting business) and believes that KM strategy is essential for an effective KM practice.
  • . . Service Systems . .
  • Lori Lewis leads Global Digital and Integrated Marketing for the Applications and Business Services division in HP’s Enterprise Services. The organization is focused on providing clients with enterprise applications services and solutions to solve some of their most pressing business problems. For over 2 decades, she has championed innovative communication approaches to drive and grow market share and build motivated, empowered teams. She is a compelling, passionate ambassador of the art and science of marketing and the amazing results it can achieve when done with integrity and passion. Ms. Lewis’ credentials, track record, and enthusiasm are essential ingredients her team relies on as they work together to establish HP as the undisputed leader in information management and analytics services.
  • Microsoft Dynamics CRM solution architect, C# developer, MBA, husband, father, Auburn man. Follow me on Twitter @lucas_is.
  • CRM enthusiast, avid techie
  • More than 10 years of experience in developing effective and innovative marketing and communication strategies. Recently I have studied the effects of social media and disruptive technology on business, marketing, and culture. Follow me on Twitter: @micaelaraimondi
  • Agile Champion and coach. Passion in software development using lean and agile techniques. Software is a people business!!
  • Have 11 years of experience in SAP Consulting, Solutioning and Account management.
  • I have over 20 years of I.T. experience predominantely in applications development. In addition to my I.T. experience I spent 7 years as the Director of Store Services at Canada's third largest grocery retailer.
  • Shafraz Nasser is the Lead Microsoft CRM Architect with HP Enterprise Services in the South Pacific Microsoft Dynamics Practice. His focus is on selling, architecting and overseeing delivery of Microsoft Dynamics CRM based implementations within New Zealand.
  • Shefali Dua is leading Worldwide BPaaS Strategy & Solution Innovation team at HP Enterprise Services as the Solution Innovation Manager. Her focus is currently assisting in planning and delivery of industry solutions for verticals like social media, big data, mobility and security on the HP Enterprise Cloud offerings for CRM Technologies.
  • Steve Petruno is a Product Manager for HP’s Global Oracle Services with over 24 years experience in the Information Technology industry, project Management, Human Resources, Payroll and Benefits, ERP implementations, upgrades, acquisitions and divestitures.
  • I have worked for HP as a business consultant for seven years, providing process, strategy and business transformation advice in the Financial Services and UK Government sectors. As part of this I have used Lean and Continuous Improvement techniques to assess and improve business performance, ensure regulatory compliance and improve environmental sustainability.
  • Tom is the Global Product Marketing lead for HP's Cloud Applications Services. Tom has over 20 years of experience in information technology and a proven track record for implementing innovative client solutions in several industries including government, healthcare, and telecommunications. He thrives on developing services and solutions which result in business process improvement through greater systems efficiency.
  • Vijay Seetharaman is an Enterprise Architect within HP Enterprise Services - Industry Transformation Consulting practice, focusing on Cloud and Mobility

Follow Us