Only letters and numbers of Django RegexField

I need a regexfield in django form to accept only letters and numbers, and nothing more. I tried this, but this did not 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 don't use regular expressions very well. Can you tell me what I'm doing wrong here and how to fix it?

+3
source share
3 answers

regular expression = g '[A-Za-Z0-9]',

This is one letter.

Do you need more than one letter? Then use repeat

regular expression = g '[A-Za-Z0-9] +,

There are many regex guides. Please go to Google for Regular Expression.

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

+3

" "? ?

The “error” that I can immediately notice is that it accepts only one character. You are missing the repetition in the argument regex. Try adding *or +at the end (for more details see the python module documentation re).

0
source

Source: https://habr.com/ru/post/1767278/


All Articles