Reputation: 501
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?
Upvotes: 0
Views: 318
Reputation: 2302
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.
Upvotes: 1
Reputation: 1063
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
Upvotes: 0
Reputation: 21754
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'
)
]
)
Upvotes: 2