Python Django表单无空间验证器(RegexValidator)

Python Django表单无空间验证器(RegexValidator),python,regex,django,forms,Python,Regex,Django,Forms,我写了这个验证器: no_space_validator = RegexValidator( r'^[^\s]+$', _('No spaces allowed'), code='invalid_username') 我在表单字段中设置了它: username = CharField( label='Username', validators=[no_space_validator]) 但它仍然允许我提交带有空格的用户名。我看不出我的正则表达式是怎么错

我写了这个验证器:

no_space_validator = RegexValidator(
    r'^[^\s]+$',
    _('No spaces allowed'),
    code='invalid_username')
我在表单字段中设置了它:

username = CharField(
    label='Username',
    validators=[no_space_validator])
但它仍然允许我提交带有空格的用户名。我看不出我的正则表达式是怎么错的,也看不出我怎么能用任何其他方式表示没有空格。

你可以这样做(注意大写字母S):

有关更多信息,请阅读文档:
以下是更简单的方法:

  no_space_validator = RegexValidator(
      r' ',
      _('No spaces allowed'),
      inverse_match=True,
      code='invalid_tag',
  )

.. 你确定问题出在正则表达式上吗?当你像这样编写验证器时会发生什么:
RegexValidator(regex=r'^[^\s]+$,message='(不允许有空格),code='invalid_username')
@xyres,同样的情况也会发生。无验证。下划线是什么?噢,它通常在Django中用于翻译,像从Django.utils.translation导入ugettext\u lazy as导入

  no_space_validator = RegexValidator(
      r' ',
      _('No spaces allowed'),
      inverse_match=True,
      code='invalid_tag',
  )