You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Validating Input with Regular Expressions

Validating Input with Regular Expressions

Have you ever wished CFINPUT provided a way to validate an e-mail address? Or were you frustrated that its telephone validation didn't allow parentheses around an area code among other such limitations?

Well, your wish has been granted in a new, little-known feature of CF5.

While many will know of the top 10 or so new features in CF5, few will know about the dozens (yes, dozens) of less-promoted enhancements. One of these is the ability to validate user input by way of regular expressions. (If you're new to regular expressions, we'll show you some examples and point you to the CF docs where you can learn more.)

The new feature isn't something that you couldn't do previously, if you knew how to code input validation tests in JavaScript. But, like so many features in CF, the point is that a single tag can solve the problem for you much more easily.

New Capabilities for Tags
What's new is that the CFINPUT and CFTEXTINPUT tags, which are both used within a CFFORM tag, now offer the ability to validate their input using regular expressions. That means you're no longer limited to the validations built into the tags (such as date, time, telephone, zip code, credit card, Social Security number, etc.)

If you're not familiar with these validations, they're quite useful (with some caveats). The CFINPUT tag, for instance, builds JavaScript for you that's sent to the browser to ensure that the user's input for a given field matches an expected pattern for the chosen validation. You can read more about these tags in the CF docs or your favorite CF book (see Sidebar).

Are you using the CF documentation?

There are lots of great CF books on the market but did you know that CF comes with several very useful manuals? Often, the print version ends up on the shelf of the CF administrator rather than in the hands of CF programmers. If you can get the printed manuals (the set is also available for $50 from Macromedia), they're quite handy and include a reference manual as well as a programmer's guide and more.

They're also available in HTML format by several means: first, they're installed within Studio (one way to reach them is to use the menu command Help>Open Help References Window). They may also be on your CF server (at http://<yourserver>/CFDOCS/dochome.htm), though they shouldn't typically be installed on production servers for security reasons outlined in an Allaire Security Zone bulletin.

The good news is that you can also now find them online at http://livedocs.allaire.com, a new service that also allows you to post comments on each page! Lastly, the docs are also available in PDF format at http://www.allaire.com/developer/documentation/coldfusion.cfm.

Of course, the new capabilities are discussed only in the CF5 docs. If you have not yet installed CF5, you can view the documentation mentioned throughout this article by visiting http://livedocs.allaire.com. Also, if you install the new CF5 update for Studio 4.5.2 (www.macromedia.com/software/coldfusion/resources/ cf_tag_update/contents.html), it will install new help that appears as a new book in the Studio Help feature: "Cold-Fusion 5 (new manuals)."

There's one potential source of confusion, however. While the update does offer new CF5 documentation that covers this new feature as well as new tag insight, tag completion, tag editors, and tag help for most CF5 tags and functions, the tag editor and tag insight features don't include these new attributes for CFINPUT and CFTEXTINPUT. The same is true in CF Studio 5 as of RC1. However, the features do work in CF5.

Getting back to input validation, the built-in validation available for CFINPUT and CFTEXTINPUT has always been somewhat limited (phone numbers had to include an area code, but you couldn't surround them in parentheses) or just nonexistent (there's no built-in validation for e-mail addresses, among other things).

As of Release 5 of CF, you can now create any form of validation you want, if you know how to create the regular expression to describe the pattern that the input should follow. Want to validate Federal Employer Identification Numbers (FEINs, which are not the same format as SSNs)? You can. Want to let people enter phone numbers with or without area codes, and allow parentheses around the area code? You can.

Validating an E-Mail Address
Want to add an e-mail validation? You can do that, too. It's as easy as specifying that the validation will be using regular expressions (using VALIDATE="regular_expression") and then offering the expression in a new PATTERN attribute. Here's an example that will validate e-mail addresses:


Email: <CFINPUT TYPE="Text" NAME="email"
PATTERN=" ^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.
MESSAGE="Email is improperly formatted">
<INPUT TYPE="Submit">

That regular expression in the PATTERN attribute may seem quite daunting. For now, just accept that regular expressions that do something useful may exist - and the cool thing is you can copy them from others to get the benefit.

For example, I borrowed the e-mail matching pattern from one created by Jeff Guillaume for his IsEmail user-defined function offered at the www.CFLib.Org Web site. (If you're not aware of this great repository of user-defined functions run by CF mavens Ray Camden and Rob Brooks-Bilson, do check it out!)

Note that the pattern isn't perfect: for instance, it won't catch if the user types [email protected] (leaving off the c in ".com"). The pattern does allow two or three character domain names (to allow for international domains like ".ca" and ".au".) What may surprise others is that last list of values (.aero, .coop, .info, .museum, .name). These are the newer top-level domain names that have been created recently by the InterNIC. There are still others, but they're either two or three characters.

One other thing to note: it would be best to copy and paste this code rather than try to type it. Regular expressions are pretty picky, and if you get it wrong, you don't generally get an error mesage - the expression just fails to work as expected. For instance, the character used between "aero" and "coop" is a bar (|), not a lowercase letter L (l), nor the number one (1).

How CFFORM Works
I mentioned earlier that using CFINPUT within CFFORM would cause CF to build JavaScript that's sent to the browser on your behalf. That's the cool thing: you don't need to understand JavaScript or how to embed event handlers in your form; CF does it for you. If you want to see the code that's generated, use your browser's View Source or View Page Source menu command. The generated script is a little complicated, but it works and is compliant with all but the oldest browsers.

If the user's input fails whatever validation we've specified in the VALIDATE attribute (or now the optional PATTERN attribute), the form will not be submitted. The user will receive a JavaScript pop-up message (see Figure 1) telling them what's wrong. The message can either be a default one ("Error in fieldname text.") or one that you specify in the MESSAGE attribute, as I have in the example. The bottom line is that they won't be able to proceed past the form until the validated field passes muster.

One of the things some people don't like about the CFINPUT VALIDATE attribute (both the older built-in validation and the new PATTERN-based one) is that users receive the prompt only when they submit the form. The JavaScript that CF builds isn't smart enough to detect the error when users leave the field. It also shows only one message at a time (rather than showing all validation failures at once). Finally, it isn't smart enough to leave the cursor on the field that contains the error users are being told about (which is all the more frustrating since it's only validating one at a time anyway).

If these things really bother you (and they don't have to, if you're validating only a couple of fields), you should know that you can build your own validation to do those things, if you'd like. In fact, the CFINPUT tag offers an ONVALIDATE attribute, in which you name a JavaScript function (that you must write and include on the page) to do some specific validation. If you use this approach, any value in the VALIDATE (or PATTERN) attribute is ignored, but it does indeed give you greater control. Another alternative is the little known PASSTHROUGH attribute, which allows you to pass virtually any attribute/value pair you'd like (including one that uses JavaScript) to be made available on the generated INPUT tag.

Still another thing that dissuades some people from using CFFORM is that they're afraid of its use of Java applets. It's important to clarify here that CFINPUT only uses JavaScript for validation - no Java applets. CFTEXT-INPUT, on the other hand, like several CFFORM subtags, does rely on a Java applet. The applet often provides enhanced control over the user interface (in fact, Release 5 of CF offers many new enhancements to these Java-enabled features), but using Java on the client does have its disadvantages, so some are afraid to use it.

And despite what some may think, using CFFORM will not always cause the applet support files to load: they're loaded only when you use one of the applet-based subtags. But CFINPUT doesn't use Java - it uses JavaScript. Big difference.

There is still another potential issue: not all browsers support JavaScript (and some users have it disabled intentionally for security concerns). Still, there's no harm in using this feature if JavaScript isn't enabled. The JavaScript built by CFINPUT is written in such a way that if the browser doesn't support JavaScript, it will simply be ignored.

Of course, that means you shouldn't rely solely on the JavaScript validation since data coming from a browser that doesn't support it won't be validated. You need to also validate it on the server. A cool thing is that you can generally use these same JavaScript regular expression patterns in the CFML code that processes the form, using them in the REFind or RE-FindNoCase functions. More about these in a moment.

One last thing to note about our use of CFFORM in the preceding example: I used an empty string for the form's ACTION attribute value. CFFORM requires an ACTION attribute. It can't be left off, and even though in this particular example it doesn't really matter where we submit to, we have to provide one. Since we're only interested in observing the behavior when we try to submit it, I left the action blank so the page will just call itself. Of course, you should name the action page of whatever CF page will process the form.

About Regular Expressions
So how about that regular expression? What does "^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name)))?$" mean? It may look a little confusing, but with a little knowledge, looking at a new pattern starts to make sense quite quickly. I can't offer a tutorial on regular expressions, or regexps, as they're also known, in this article, but I can show you where to learn more.

And what are regexps, anyway? They've actually been around for a long time and extend well beyond ColdFusion (and JavaScript). In fact, they're more strongly supported and more widely used in the UNIX operating system, but they've found their way into many more tools since they provide a powerful way to perform matching against a pattern, whether simple or complex. Obviously, the preceding pattern looks rather complex. There is even an entire book on the subject, called Mastering Regular Expressions, by Jeffrey E. Friedl (O'Reilly).

The good news is that Macromedia has provided some bolstered documentation of them just for this specific new feature, in the second section of Chapter 9 ("Building Dynamic Forms") in the Developing ColdFusion Applications manual. The old name was Developing Web Applications with ColdFusion.

The manual does have some coverage of regexps, as does the CFML Reference, but it's important to note that some of the coverage there is about ColdFusion's supported regexp syntax. What do I mean by that? It's another source of confusion.

ColdFusion Regular Expressions?
Prior to Release 5 (and still supported in CF5), there are several features in ColdFusion (and Cold-Fusion Studio) that leverage regular expressions already. They include the REFind and REFindNoCase functions, as well as REReplace and REReplace NoCase. Each of these performs a find or replace (case sensitive or not), respectively, using regexps, as do the Extended Find and Extended Replace features in Studio (under the Search menu). The CFLDAP tag's FILTER attribute also uses them.

These CF-enabled features, however, use a regular expression syntax that Allaire built into ColdFusion. The syntax supported is indeed documented in the CF manuals. In CF5, it's the Developing ColdFusion Applications manual, Chapter 14, "Using Regular Expressions in Functions." In fact, this documentation is greatly improved over the documentation in previous releases (there was no similar chapter).

Take note, however: this CF-specific version of regular expressions isn't a complete rendering of regular expressions as is used in UNIX or even JavaScript. And that's a key point for the purposes of this article: the regular expressions used in CFINPUT's PATTERN attribute are JavaScript regular expressions, passed verbatim to the client and interpreted on the browser.

But they're similar enough, and as was mentioned, the new documentation does offer a brief rundown (in Chapter 9 of that book) of some typical JavaScript regular expression syntax that might be used in the CFINPUT PATTERN attribute. The discussions are more complete in Chapter 14, and it's not too difficult to apply what's learned in one chapter to the equivalent features described in the other.

So, I'll leave it to your exploration of the docs to learn what the regular expression "^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name)))?$" used above means.

Be sure to carefully test your use of regular expressions in the environment in which you will deploy them. For the most part, if a regexp works in one browser, it will work in all of them. Note that the CF regular expressions (used in the functions) offer a format called POSIX-compliant regexps. These should not be used in the CFINPUT PATTERN since they'll be passed down to the browser and my testing suggests they're not supported in JavaScript (at least they weren't in my Internet Explorer 5.5).

Some Advanced RegExp Tips
I'd like to add a couple of comments for the benefit of more experienced regexp developers. First, note that I have not used the opening and closing slash ("/") that you may be used to using to delineate an expression. That's because, if you look at the JavaScript created by CF, it's putting those in for you. If you add them as well, it will make the pattern fail. Forewarned is forearmed.

Second, note that I've wrapped the entire pattern (other than the start/end characters, ^ and $) in parentheses. More important, I've followed that closing parenthesis with a "?". This is important as it indicates that the pattern being sought can occur either 0 or 1 time. If you leave that off, then you'll perhaps inadvertently indicate that an e-mail address is required. If none is entered, the pattern won't match and the validation will fail.

You may indeed want to require that a value be entered, but there's an available REQUIRED attribute for the CFINPUT that will make it more clear to someone looking at your code that you're requiring an input value. I just mention this because if you didn't think to add it (the ()? around the pattern), it would fail even if no value was entered and you may be quite confused by that. (Okay, if you're really experienced with regexps, maybe not!)

Finally, keep in mind that in the case of both kinds of regexps (used in the CF functions or in CFINPUT's PATTERN attribute), it's certainly acceptable to use ColdFusion variables and other expressions to create the values to be used in the regexp. The CF expressions are interpreted by CF before the regular expression is then interpreted, so you can use form and query variables, and so on, to help build your regexp.

Validating Phone Numbers
I mentioned at the opening that the built-in VALIDATE="telephone" is limited in some ways (forcing the user to provide an area code and not allowing parentheses around the area code). Here's a pattern that gets around those problems and still adds some other value:


It, too, isn't perfect. It doesn't support international area codes, nor numbers formatted in other than the typical U.S. format for phone numbers of three-digit area codes, three-digit exchanges, and four remaining numbers. But while it does allow parentheses, dashes, and spaces, it doesn't require them. More experienced regexp users may wonder why I didn't just use "\d{3}" for the pattern to search for the three digits of the area code and exchange (the first three of the last seven numbers). The problem is that this wouldn't ensure they didn't start at zero, which is another rule for U.S. telephone numbers (for now, anyway).

Closing Thoughts
As I noted before, you don't need to understand these patterns in detail to benefit. Just go ahead and use them.

Maybe eventually there will be a repository of patterns that can be used in a variety of ways, including the PATTERN attribute, the RE functions, Studio, and even more fancy user-defined functions, such as the IsEmail from which I got the example e-mail pattern.

Better still, perhaps you'll be motivated to create other patterns to solve common problems, to offer to such a repository, or to simply solve your own challenges. I hope this quick tutorial on a new way to use them in CF5 motivates you to consider them, or at least be able to benefit from those who do.

Additional Resources

  1. To learn more about adding your own validation, see Selene Bainum's article, "Extending CFFORM with Customized JavaScript Validation" (CFDJ, Vol. 2, issue 8) at www.sys-con.com/coldfusion/article.cfm?id=141.
  2. To learn more about JavaScript in general, see my article, "Getting Focus(ed)" (CFDJ, Vol. 2, issue 6) at www.sys-con.com/coldfusion/article.cfm?id=122.
  3. To learn more about doing form and input validation with CF, see Kailasnath Awati and Mario Techera's article, "Some Thoughts on the Design of CF Data Input Applications" (CFDJ, Vol. 3, issue 3), at www.sys-con.com/coldfusion/article.cfm?id=234.

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
Kris Symer 04/08/05 01:15:04 PM EDT

My coworker and I refined the email script so it would work for upper and lowercase letters in an optional cfinput field (required="no"):


charles arehart 08/01/02 05:47:00 PM EDT

Folks, I have found that there were a couple of errors in the expressions offered here. Please use the following instead.

For email:


For phone:


Sorry for the inconvenience.

@ThingsExpo Stories
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...