Grace Whitney
Grace Whitney

Reputation: 121

How can I apply a common validator to all text inputs in my Django form?

I want to apply a special character whitelist to all non-password user text inputs across my site, so that validation will fail if a non-whitelisted character is entered. All of my forms already inherit from a single base form class, which itself inherits from django.forms.BaseForm. How can I apply this validator to every relevant field on all the forms that inherit from this form?

Upvotes: 2

Views: 187

Answers (1)

Grace Whitney
Grace Whitney

Reputation: 121

Override the __init__ method on the base form class:

class ProjectBaseForm(forms.BaseForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            if isinstance(field, forms.CharField) and not isinstance(field.widget, forms.PasswordInput):
                field.validators.append(validate_special_characters)
def validate_special_characters(text):
    if set(text) - set(CHAR_FIELD_ALLOWED_CHARACTERS):
        raise ValidationError(f"Invalid characters. Only the following special characters are allowed: {" ".join(VALID_SPECIAL_CHARACTERS}")    
from string import ascii_letters, digits

VALID_SPECIAL_CHARACTERS = ' "\'#&()+,-./:;@_?!\n'
CHAR_FIELD_ALLOWED_CHARACTERS = ascii_letters + digits + VALID_SPECIAL_CHARACTERS

Upvotes: 3

Related Questions