Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django regex validator message has no effect

Tags:

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 only problem is that no matter what I try, The RegexValidator still chucks the default error ("enter a valid value").

This is my code. I also tried it without the 'message=' in front, and it still said "enter a valid value", instead of "username must be alphanumeric"

user = CharField(
    max_length=30,required=True,
    validators=[
        RegexValidator('^[a-zA-Z0-9]*$',
            message='Username must be Alphanumeric'
        ),
    ]
)
like image 366
matts1 Avatar asked Jul 20 '13 08:07

matts1


2 Answers

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'
        ),
    ]
)
like image 117
Hieu Nguyen Avatar answered Sep 19 '22 15:09

Hieu Nguyen


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."

like image 27
jrvidotti Avatar answered Sep 19 '22 15:09

jrvidotti