[英]Django Form no space validator (RegexValidator)
I wrote this validator: 我写了这个验证器:
no_space_validator = RegexValidator(
r'^[^\s]+$',
_('No spaces allowed'),
code='invalid_username')
and I have it set in the Form field: 我在“表单”字段中设置了它:
username = CharField(
label='Username',
validators=[no_space_validator])
But still it allows me to submit usernames with spaces. 但是它仍然允许我提交带有空格的用户名。 I can't see how me regex is wrong here or how can I express no spaces in any other way. 我看不到我的正则表达式在这里有什么错,或者我怎么不能以其他任何方式表达空格。
You can do it like this (note the capital S): 您可以这样操作(注意大写S):
no_space_validator = RegexValidator(
r'^[^\S]+$',
_('No spaces allowed'),
code='invalid_username')
Read the docs for more info: https://docs.djangoproject.com/en/dev/ref/validators/#regexvalidator 阅读文档以获取更多信息: https : //docs.djangoproject.com/en/dev/ref/validators/#regexvalidator
Here is more simple approach: 这是更简单的方法:
no_space_validator = RegexValidator(
r' ',
_('No spaces allowed'),
inverse_match=True,
code='invalid_tag',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.