Titivillus/user/validators.py

46 lines
1.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""
Some custom validators for the user model.
"""
from django.core.validators import BaseValidator
from django.core.exceptions import ValidationError
class MaximumLengthValidator:
"""
Validate whether the password exceeds a maximum length.
"""
def __init__(self, max_length=1024):
self.max_length = max_length
def validate(self, password, user=None):
if len(password) > self.max_length:
raise ValidationError(
"This password is too long. It must contain at most " \
+ f"{self.max_length} characters.",
code="password_too_long",
params={'max_length': self.max_length}
)
def get_help_text(self):
msg = f"Your password must contain less than {self.max_length} " \
+ "characters."
return msg
class CharValidator(BaseValidator):
"""
Raises a ValidationError with a code of 'invalid_chars' if value is not
a string or contains letters which are not also within limit_value.
"""
message = 'Ensure this value only contains the characters "%(limit_value)s".'
code = 'invalid_chars'
def compare(self, value, limit_value):
assert type(limit_value) == str
if type(value) != str:
return True
for c in value:
if c not in limit_value:
return True
return False