djangodjango-modelsdjango-validationdjango-model-field

Django model field custom validator returned value not saved


I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel.

custom validator

def phone_number_validator(value):
    if value:
        value = value.strip()
        value = value.replace(' ', '')

        digits = []
        non_digits = []
        for c in value:
            if c.isdigit():
                digits.append(c)
            else:
                non_digits.append(c)

        if len(non_digits):
            raise ValidationError('Only numbers and spaces are allowed for this field.')
        elif len(digits) < 10 or len(digits) > 10:
            raise ValidationError('Phone number should be exactly 10 digits.')
        elif (not value.startswith('07')) and (not value.startswith('0')):
            raise ValidationError('Invalid phone number.')

        if value.startswith('07'):  # mobile number
            value = f'{value[0:3]} {value[3:6]} {value[6:]}'
        elif value.startswith('0'):  # landline
            value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}'
        print(value) #### here the correct format is displayed
        return value

models.py

hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator])

Solution

  • The purpose of a validator is only to check the value against a set of criteria. It is not meant to modify value.

    Reference: https://docs.djangoproject.com/en/4.0/ref/validators/