简体   繁体   中英

Django - RegexValidator using special expressions

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?

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')
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM