Django custom validator with multiple inputs

Im trying to create a custom validator that must be able to validate different conditions given a type

def validator(value, type, param):

    match type:
        case 'regex_validator':
            if not re.search(param, value):
                raise ValidationError()
        case 'max_length':
            if value > param:
                raise ValidationError()

and my question is: How can I pass the function the form value? The examples I have seen don't implicitly pass the value to the validator.

I want to do declare the the form fiel like this:

forms.CharField(validators=[validator(value, x['type'], x['param'] for x in field_validators])

Django does not allow to make a multi fields validation with field validators. You have to do your validation in the clean_FIELDNAME function form.

class FormExample():
    field = forms.CharField()

    def clean_field(self, data):
        if XXX:
            validator = RegexValidator()
        elif YYYY:
            validator = MaxLengthValidator()

        validator(data)

Or you can create a custom field with overrided validate function for making your custom choice of validator (https://docs.djangoproject.com/en/4.1/ref/forms/validation/#form-field-default-cleaning)

Back to Top