Reputation: 6079
For the sake of DRY and easyness I want to inherit from Django's RegexValidator.
I tried this:
class UsernameValidator(RegexValidator):
regex = r'^([a-zA-Z]{4}[\w]{1,16})$'
message = 'Wrong username format.'
code = 'invalid_format'
And I added this validator to my field this way:
class RegistrationForm(forms.Form):
signup_username = forms.CharField(label='Username', max_length=20,
validators=[UsernameValidator])
But the Validator does not fail if I use an wrong Username (like 123
or abc
).
What's the right way to inherit from RegexValidator
?
I need this validation at several points, what's why I want an own validator for this.
Upvotes: 1
Views: 480
Reputation: 186
Validators argument should be a list of callable objects In your case it should be
validators=[UsernameValidator()]
Upvotes: 0
Reputation: 304
Create instance of RegexValidator.
validate_username = RegexValidator(regex=r'^([a-zA-Z]{4}[\w]{1,16})$',
message = 'Wrong username format.',
code = 'invalid_format')
...validators = [validate_username]...
Upvotes: 1
Reputation: 6079
I wrote an own function instead of subclassing RegexValidator, and that works.
def validate_username(value):
regex = r'^([a-zA-Z]{4}[\w]{1,16})$'
if not re.match(regex, value):
raise ValidationError('Wrong username format.')
Upvotes: 0