Django regex validator message has no effect

后端 未结 4 987
不思量自难忘°
不思量自难忘° 2020-12-31 04:48

I am trying to get it so that the validator tells you \"username must be alphanumeric\". This is my code so far. I have confirmed that it validates at the correct time. The

相关标签:
4条回答
  • 2020-12-31 05:00

    I was having trouble running a RegexValidator, too. But I was trying to raise the error by saving the model instance. It will not work this way! Only when using ModelForms the validators are called automatically.

    In https://docs.djangoproject.com/en/dev/ref/validators/#how-validators-are-run

    Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form."

    0 讨论(0)
  • 2020-12-31 05:01

    How about adding the error code:

    user = CharField(
        max_length=30,
        required=True,
        validators=[
            RegexValidator(
                regex='^[a-zA-Z0-9]*$',
                message='Username must be Alphanumeric',
                code='invalid_username'
            ),
        ]
    )
    
    0 讨论(0)
  • 2020-12-31 05:05
    a validate user name here should contain at least one minuscule letter, one capital letter and one numeric, if i understand your code.
    to complete Virendra Rajput answer correct the regex with that:
    regex=r'^[a-zA-Z0-9]*$'   start with the r'
    
    0 讨论(0)
  • 2020-12-31 05:20

    Try passing the messsage as,

    user = CharField(
        max_length=30,
        required=True,
        validators=[
            RegexValidator(
                regex=r'^[a-zA-Z0-9]*$',
                message=_('Username must be Alphanumeric'),
            ),
        ]
    )
    
    0 讨论(0)
提交回复
热议问题