How to validate characters ONLY in ColdFusion CFForm?

Chris Brandt picture Chris Brandt · Jul 7, 2009 · Viewed 7.9k times · Source

I've got a very simple cfform with a single form field:

<cfform action="asdf.cfm" method="post">
  <cfinput name="fieldName" type="text" size="20" maxlength="20" required="yes" validate="regex" pattern="[A-Za-z]" message="Only characters are allowed." />
  <input type="submit" name="btnSubmit" value="check" />
</cfform>

Theoretically, this would allow ONLY A-Z and a-z in any combination, and must have some content in it.

In practice, I'm able to enter 'a a' and the javascript validation does not complain. Since the 'space' character is not in A-Z and not in a-z, what's going on?

Thanks! Chris

Answer

Tomalak picture Tomalak · Jul 7, 2009

You are missing the start-of-string and end-of-string anchors:

^[A-Za-z]$

or, more likely:

^[A-Za-z]{1,20}$

Your sample, modified:

<cfform action="asdf.cfm" method="post">
  <cfinput name="fieldName" type="text" size="20" maxlength="20" required="yes" validate="regex" pattern="^[A-Za-z]{1,20}$" message="Only characters are allowed." />
  <input type="submit" name="btnSubmit" value="check" />
</cfform>

Without those anchors, the regex merely needs to match anywhere, it does not need to match entirely.