0

i try to force the user to use only alphanumeric characters in a certain

field so i wrote the following code in the User model:

alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='Only alphanumeric characters are allowed.')

username = models.CharField(unique=True, max_length=20, validators=[alphanumeric])

but i still can create:

User.objects.create(username="@@")

i don't want it to create something like it...

am i doing something wrong? did i wrote a wrong regex validator?

brad
  • 491
  • 1
  • 9
  • 24

3 Answers3

2

I think your code should look like this:

username = models.CharField(unique=True, max_length=20, 
    validators=[
        RegexValidator(
            r'^[0-9a-zA-Z]*$', 
            message='Only alphanumericcharacters are allowed.',
            code='invalid_username'
        )
    ]
)
xyres
  • 20,487
  • 3
  • 56
  • 85
1

Validating performs when you call model's full_clean() method or when you use ModelForm's is_valid(). Creating new model instance in shell or in view will not raise ValidationError. More.

f43d65
  • 2,264
  • 11
  • 15
0
    user = CharField(
        max_length=30,
        required=True,
        validators=[
            RegexValidator(
                regex='^[a-zA-Z0-9]*$',
                message='Username must be Alphanumeric',
                code='invalid_username'
            ),
        ]

)

Source:Django regex validator message has no effect

Community
  • 1
  • 1
chandu
  • 1,053
  • 9
  • 18