Search code examples
djangodjango-modelsdjango-validation

Multiple validators for Django 1.11 Model CharField


Does anyone know if it is possible to apply multiple validators to a Django 1.11 Model CharField? I am trying to enforce formatting of the field as either: "Use format XX XXXX XXXX" or "Use format XXXX XXX XXX"

prefphone = models.CharField(max_length=255,null=True,blank=True,validators=[RegexValidator(r'^[0-9]{2} [0-9]{4} [0-9]{4}$', "Use format XX XXXX XXXX"),RegexValidator(r'^[0-9]{4} [0-9]{3} [0-9]{3}$', "Use format XXXX XXX XXX")])

The first validation is failing and the second validation is not tested.

If there are alternative methods to achieve my outcome I would be grateful to hear them. Thanks!


Solution

  • Here's my approaching for multiple validator: Define a custom validator function:

    from django.core.exceptions import ValidationError
    
    validator_fn = [
        RegexValidator(r'^[0-9]{2} [0-9]{4} [0-9]{4}$', "Use format XX XXXX XXXX"),
        RegexValidator(r'^[0-9]{4} [0-9]{3} [0-9]{3}$', "Use format XXXX XXX XXX")
    ]
    
    def regex_validators(value):
        err = None
        for validator in validator_fn:
            try:
                validator(value)
                # Valid value, return it
                return value
            except ValidationError as exc:
                err = exc
        # Value match nothing, raise error
        raise err
    

    Now in field, just use regex_validators as a single validator:

    prefphone = models.CharField(max_length=255,null=True,blank=True,validators=[regex_validators,])