简体   繁体   English

Django - 使用特殊表达式的 RegexValidator

[英]Django - RegexValidator using special expressions

How do I implement special expressions in RegexValidator ?如何在RegexValidator实现特殊表达式?

forms.py:表格.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.我也想使用:áàäéèëíìïóòöúùüñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑ,但我收到“非ASCII字符”错误。 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:您可以使用\\w说明符,但由于RegexValidator不启用re.UNICODE标志,您可能需要这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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