Hello. I am trying to validate the adult age, but the error message does not show. In the validator I calculate the person’s age and check if they’re adult.
# realestate\realestate\validators.py
class AdultValidator(BaseValidator):
def __init__(self, limit_value=18, message=None):
super().__init__(limit_value, message)
def __call__(self, value: date):
today = date.today()
print(value)
age = today.year - value.year - ((today.month, today.day) < (value.month, value.day))
if age < self.limit_value:
raise ValidationError(_("birth_date.adult").format(_("birth_date")))
The use in the form.
class RegisterForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 2 Input validation & sanitization
self.fields["password1"].error_messages = {"required": _("field.required").format(field=_("password1"))}
self.fields["password2"].error_messages = {"required": _("field.required").format(field=_("password2"))}
self.fields["email"].validators = [EmailValidator(message=_("email.email"))]
self.fields["phone"].validators = [RegexValidator(regex=r"^\+381 \d{2} \d{6,7}$", message=_("phone.regex"))]
self.fields["first_name"].validators = [AlphaValidator(message=_("field.alpha").format(field=_("first_name")))]
self.fields["last_name"].validators = [AlphaValidator(message=_("field.alpha").format(field=_("last_name")))]
self.fields["birth_date"].validators = [AdultValidator]
No error message for the birth date (Datum rođenja) is shown.
