views:

38

answers:

2

I need a regexfield in a django form to only accept letters and numbers, and nothing else. I've tried this, but it didn't work:

myfield = forms.RegexField(label=("My Label"), max_length=31, regex=r'[a-zA-Z0-9]',
        error_message = ("This value must contain only letters and numbers."),

I am not very good at using regular expressions. Can you tell me what I am doing wrong here and how to fix it?

+1  A: 

regex=r'[a-zA-Z0-9]',

Is one letter.

Do you want more than one letter? Then use a repeat

regex=r'[a-zA-Z0-9]+',

There are numerous tutorials on regular expressions. Please google for "Regular Expression Tutorial."

S.Lott
I did google for it, hence the solution I came up with. It clearly wasn't correct though. Using your solution: regex=r'[a-zA-Z0-9]+', I can still use use underscores, any idea why?
bababa
Because. Your pattern does not specify the WHOLE string. You need `^` and `$`. "I did google for it". Keep trying, then. There are **good** tutorials that will help you.
S.Lott
A: 

What do you mean by "it didn't work"? Can yoube more specific?

An "error" I can spot right away is that it will only accept a single charactter. You're missing a repetition in the regex argument. Try adding a * or + at the end (see python's re module documentation for details.

André Caron
It didn't work means that the form does not validate correctly. As in I enter "asdasdf" and it still throws a validation error.
bababa
I figured it out. I needed the carrot and dollar sign at the end: regex=r'^[a-zA-Z0-9]+$',
bababa
@bababa: It's caret, not carrot :)
Tim Pietzcker