CFFORM Regex won't validate properly

118 Views Asked by At

Ive got an old form that still must use cfform for its client side validation.

Ive also got a regular expression pattern for validation and Im trying to validate for a phone number string.

<cfinput class="form-field" required="yes" value="#session.userdetails.shipping.deliveryaddress.telephoneNumber#" message="Please Enter your Phone Number" name="telephoneNumber" type="text"  id="PhoneNumber" validate="regex" pattern="^[0-9\.\-' ']+$"  maxlength="25" size="26" />

Ive tried a number of different patterns to validate the string to a particular format.

I need it to be a minimum of 7 characters it can contain spaces must be numeric

^[0-9\.\-' ']{7}+$
^[0-9\.\-' ']{7,}+$

Any ideas on why this wont validate to my requirements ?

1

There are 1 best solutions below

0
On

"Any ideas on why this wont validate to my requirements ?"

Because the regex you're using contains syntax not supported by JS - if you look in the browser console you'll see an error when it attempts to validate. (You may need to select the "persist" option to see it.)

Your mistake is that you've either put two quantifiers together, or perhaps have seen what's known as a possessive quantifier and tried to use that, (but JS doesn't support them).

The solution is to simply use {7,} without the + after it, and your pattern will almost work as intended: the quotes around the space in the character class are not needed (and are specifically allowing that character), and the dot does not need escaping in a character class - so the pattern you want is either ^[0-9.\- ]{7,}$ or ^[\d .-]{7,}$.


By way of a quick note about possessive quantifiers compared to other types:

  • x{7,} is a quantifier with greedy behaviour, meaning it matches x as many times as possible, but at least seven times required.
  • x{7,}+ is a quantifier with possessive behaviour, meaning it matches x as many times as found, but at least seven times required.
  • x{7,}? is a quantifier with lazy behaviour, meaning it tries to match x seven times, and after that as few as it can get away with to succesfully match.
  • x+ is a shorthand for x{1,} and you can have x++ and x+? to change from the default greedy quantifier.

Again, the regex implementations used by JS and CF don't support possessive quantifiers (hence why invalid syntax), but they do support both greedy (default) and lazy.

The difference between possessive and greedy might seem subtle - and for a single-item pattern as you have it doesn't actually come into effect - but it can make very significant differences in the execution ... but that's veering off the track of the core answer, so I'll stop myself here.