Reputation: 15824
In a Django form, I'm getting users to input their usernames. The field is like so:
username = forms.RegexField(max_length=50,regex=re.compile('^[\w.@+-]+$'),\
error_messages={'invalid': _("(tip: only use alphabets, numbers or @ _ . + - symbols)")})
Later, in the clean_username
method, I also need to ensure users didn't include a whtiespace in the username. I do that like so:
def clean_username(self):
username = self.cleaned_data['username']
if ' ' in username:
raise ValidationError("(tip: a username can't have whitespaces)")
return username
The problem is that this validation error never appears, since whitespaces fail the prior regex check. I need to be able to show the whitespace related ValidationError separately. Moreover I also don't want to compromise on showing the relevant error if a user writes a regex failing username such as Bèndèr*
.
What's the best way to fix this issue? An illustrative example would be great. Thanks!
Upvotes: 1
Views: 185
Reputation: 18972
So instead of using the RegexField
I would probably either go with a CharField
and a customized clean
-method for the field, which handles the whitespace issue first and only checks the regex if the the whitespace check passed.
Or I would use a CharField
and assign a custom validator first, that checks for the whitespaces, and additionally a RegexValidator
Something along these lines:
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
def validate_whitespaces(value):
if ' ' in value:
raise ValidationError("Oops, a whitespace error occured.")
username = forms.CharField(
max_length=50,
validators=[
validate_whitespaces,
RegexValidator(
regex='^[\w.@+-]+$',
message='Only use valid chars ...'
)
]
)
Upvotes: 2