Thursday, August 01, 2002

Validating Form Input With Regular Expressions

OK, so this one's not new to CFMX, but it's a CF5 feature that many missed.

If you've ever wanted to validate form input such as email addresses and phone numbers, but have found the built-in validations of CFFORM to be lacking, note that CF5 has added new functionality to perform regular expression validation within CFINPUT. All you need is the right expression. If you're not familiar with them, no worries. Here's how to validate both a phone number and email address. The key is the new VALIDATE="regular_expression" and associated PATTERN attributes.

Phone: <CFINPUT TYPE="Text" NAME="phone" VALIDATE="regular_expression" PATTERN="^(\(?\d{3}\)?)?\s?\d{3}[\s\-]?\d{4}$" MESSAGE="Phone is improperly formatted">

Email: <cfinput type="text" name="email" message="Email address is impoperly formatted." validate="regular_expression" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name))$">

<INPUT TYPE="Submit">

You can actually run that example, leaving the ACTION="". It will just try to submit to itself. If you give it a valid email and phone, it will submit. If you don't, it won't and will offer an error mesage. Of course, you can change the MESSAGE to suit your taste and would want to change the ACTION and NAME values to those appropriate to your application.

For more information, see my article in the Dec 2001 CDFJ, "Validating Input with Regular Expressions: Little Known Features of CF 5 ". You can read all 30+ of my CFDJ articles online from the "articles" link on my site, Note, however, that the expressions offered above differ slightly from those offered in the article. I have offered these corrected versions in the "comments" area at the front page of the online article.

No comments: