Reputation: 789
How do I implement special expressions in RegexValidator
?
forms.py:
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 but I get a "Non-ASCII character" error. Is there any other way to use it?
Upvotes: 2
Views: 1968
Reputation: 59219
You can use the \w
specifier, but since RegexValidator
does 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')
...
Upvotes: 4