开发者

Escaping apostrophes in regex?

I'm trying to validate a form using a regular expression found here http://regexlib.com/. What I am trying to do is filter out all characters except a-z, commas and apostrophes. If I use this code:

<cfinput name="FirstName" type="text" class="fieldwidth" maxlength="90" required="yes"    validateat="onsubmit,onserver" message="Please ensure you give your First Name and it does not contain any special characters except hyphens or apostrophes." validate="regular_expression" pattern="^([a-zA-Z'-]+)$" />

I get the following error: Unmatched [] in expression. I figured out this relates to the apostrophe because it works if I us开发者_开发百科e this code(but does not allow apostrophes):

<cfinput name="FirstName" type="text" class="fieldwidth" maxlength="90" required="yes"    validateat="onsubmit,onserver" message="Please ensure you give your First Name and it does not contain any special characters except hyphens or apostrophes." validate="regular_expression" pattern="^([a-zA-Z-]+)$" />

So I'm wondering is there some special way to escape apostrophes when using regular expressions?

EDIT

I think I've found where the problem is being caused (thanks to xanatos), not sure how to fix it. Basically CF is generating a hidden field to validate the field as follows:

<input type='hidden' name='FirstName_CFFORMREGEX' value='^([a-zA-Z'-]+)$'>

Because it is using single apostrophes rather than speech marks round the value, it is interpreting the apostrophe as the end of the value.


I think there is a bug in the cfinput implementation. It probably uses the string you pass in pattern in a Javascript Regex but it uses the ' to quote it. So it converts it in:

new Regex('^([a-zA-Z'-]+)$')

Try replacing the quote with \x27 (it's the code for the single quote)


The unmatched ] is because the hyphen is treated to mean a range between the two characters around it. Put the hyphen at the beginning as a best practice.

^([-a-zA-Z']+)$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜