views:

276

answers:

1
from django import forms
class ActonForm(forms.Form):
    creator = forms.RegexField('^[a-zA-Z0-9\-' ]$',max_length=30, min_length=3)

data = {'creator': 'hello'
        }
f = ActonForm(data)
print f.is_valid()

Why doesn't this work? have i made a wrong regular expression? I wanted a name field with provision for single quotes and a hyphen

+1  A: 

It kind of shows in the syntax highlighting. The apostrophe in the regex isn't escaped, it should be like this:

forms.RegexField('^[a-zA-Z0-9\\-\' ]$',max_length=30, min_length=3)

Edit: When escaping things in the regular expression, you need double backslashes. I doubled the backslash before the hyphen (not that it has to be escaped in this particular case.)

Secondly, your regular expression only allows for a single character. You need to use a quantifier. + means one or more, * means 0 or more, {2,} means two or more, {3,6} means three to six. You probably want this:

forms.RegexField('^[a-zA-Z0-9\\-\' ]+$',max_length=30, min_length=3)

Do take care that the above regular expression will allow spaces in the start and end of the field as well. To avoid that you need a more complex regex.

Blixt
The hyphen is also in the wrong place - hyphens in character classes aren't backslash escaped, instead they should be the first or last character.
Nick Johnson
Hyphens can be escaped just like any other special meaning character. However, placing them first or last in a character class can be considered good practice as it improves readability slightly.
Blixt