Using Regular Expressions in Sitecore’s Dictionary for Web Validation

Thursday, January 15, 2015 @ 09:00

By Corey Adler

One of the things that I like the most about working on Sitecore projects is the fact that I find something new about Sitecore on a near-daily basis. It makes working with it every day a terrifically fun experience. Case in point: On a project recently, I was tasked to fix a relatively simple issue: A form that they had included a text box for entering in an e-mail address, but the validation on the text box (to make sure that what was entered was, in fact, an e-mail address) was not working—declaring that even perfectly good e-mail addresses were invalid. When I cracked open the specific page, I found the following lines of code:

Original Code

I immediately recognized that there was a regular expression being injected into the code from my site’s Dictionary (hence the use of the JavaScript Match function), and that that was being used for the comparison. When I took a look at the Dictionary, however, I was perplexed. I couldn’t see anything wrong with the regular expression in the Dictionary, as shown below.

Original Regex

So I decided to test it out by manually using that regular expression hard-coded on the page, as well as utilizing JavaScript’s RegExp object (reference here:, since that’s what it was created for. The code for that is shown below.

Modified Code

I was immediately startled: It worked perfectly! So the next thing I did was to switch out the hardcoding, and to put back in the Dictionary reference. There was only one problem: It stopped working again when I switched it back. Obviously keeping a hard-coded value like that is not a good practice, but what else was there to do if Sitecore’s injection wasn’t working either? That’s when I looked a little closer at what was being injected into the RegExp object. It turned out that none of the backslashes were being placed in the string!

Being all too familiar with this kind of thing happening in other, non-Sitecore, .NET projects, I immediately suspected that something in the background was interpreting those backslashes as text commands and not as actual backslashes. So I went and doubled each instance of a backslash in the Dictionary phrase to escape it. It all ended up looking like this:

In Sitecore:
Final Code

On the page:
Final Code

Sure enough, that fixed it! So, for future use, just remember to be very careful about putting backslashes into your Dictionary—always make sure to double them up!

Until next time, I wish you good coding.