Django Form no space validator (RegexValidator)

2019-09-17 03:10发布

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.

2条回答
够拽才男人
2楼-- · 2019-09-17 03:44

You can do it like this (note the capital 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

查看更多
Melony?
3楼-- · 2019-09-17 03:46

Here is more simple approach:

  no_space_validator = RegexValidator(
      r' ',
      _('No spaces allowed'),
      inverse_match=True,
      code='invalid_tag',
  )
查看更多
登录 后发表回答