BrianCas BrianCas - 1 year ago 74
Python Question

Django - RegexValidator using special expressions

How do I implement special expressions in RegexValidator?

class MyRegistrationForm(forms.ModelForm):
alphanumeric = RegexValidator('^[A-Za-z]+$', 'Only alphabetic')
first_name = forms.CharField(max_length = 20, validators=[alphanumeric])
last_name = forms.CharField(max_length = 20, validators=[alphanumeric])

I would like to use: áàäéèëíìïóòöúùüñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑ as well

I get an Non-ASCII character Error

Is there any other way to use it?


You can use the \w specifier, but since RegexValidator do not enable the re.UNICODE flag, you might need something like this:

import re
class MyRegistrationForm(forms.ModelForm):
    re_alphanumeric = re.compile('^\w+$', re.UNICODE)
    alphanumeric = RegexValidator(re_alphanumeric, 'Only alphabetic')

Update: If you want to exclude numeric characters, use

import re
class MyRegistrationForm(forms.ModelForm):
    re_alpha = re.compile('[^\W\d_]+$', re.UNICODE)
    alpha = RegexValidator(re_alpha, 'Only alphabetic')