views:

771

answers:

2

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

+8  A: 

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.

Tomalak
+2  A: 

personally I would avoid using the built in coldfusion javascript. You will have much more control if you roll your own and it will give you the ability to display errors in other ways than an alert box.

<script>
function checkit() {
    var v = document.getElementById("text1").value;
    if(!v.match(/^[a-zA-Z]+$/)) {
     alert(v + ' contains invalid characters');
     return false;
    }
    return true;
}
</script>
<form onsubmit="return checkit()">
<input type="text" id="text1">
<input type="submit">
</form>
Nick
Thanks for the option (and sample code). For now, and for us, the alert box is sufficient.
Chris Brandt
For anyone else that comes along looking for a better way to do validation, I would recommend jquery's validation features. Simple and unobtrusive, but powerful and customizable.
Adam Tuttle
I second the jquery advice. I didn't mention it because javascript was already outside of the scope of the question and I wanted to keep it simple.
Nick