开发者

Django RegexField Letters and Numbers only

开发者 https://www.devze.com 2023-01-18 07:38 出处:网络
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:

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.Reg开发者_Python百科exField(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?


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."


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

this will only accept letters and numbers and will require at least one symbol


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.

0

精彩评论

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