以django表单,我正在吸引用户输入他们的用户名。该领域就像:
username = forms.RegexField(max_length=50,regex=re.compile('^[w.@+-]+$'),
error_messages={'invalid': _("(tip: only use alphabets, numbers or @ _ . + - symbols)")})
稍后,在clean_username
方法中,我还需要确保用户在用户名中不包含一个空间。我这样做是这样的:
def clean_username(self):
username = self.cleaned_data['username']
if ' ' in username:
raise ValidationError("(tip: a username can't have whitespaces)")
return username
问题在于,此验证错误永远不会出现,因为Whitespaces失败了先前的Regex检查。我需要能够分别显示与Whitespace相关的验证。此外,如果用户写入等正式用户名(例如Bèndèr*
),我也不想妥协显示相关错误。
解决此问题的最佳方法是什么?一个说明性的例子将很棒。谢谢!
因此,不使用RegexField
,我可能会选择CharField
和该领域的自定义的clean
-Method,该领域首先处理Whitespace问题,并且仅检查Regex,如果whitexpace the Regex检查通过。
否则我将使用CharField
并首先分配自定义验证器,该验证器检查Whitespaces,以及RegexValidator
沿着这些行:
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
def validate_whitespaces(value):
if ' ' in value:
raise ValidationError("Oops, a whitespace error occured.")
username = forms.CharField(
max_length=50,
validators=[
validate_whitespaces,
RegexValidator(
regex='^[w.@+-]+$',
message='Only use valid chars ...'
)
]
)