Last active
August 29, 2015 14:10
-
-
Save mathiasose/6f680c40090155d41342 to your computer and use it in GitHub Desktop.
Django MinLengthValidator that ignores HTML tags when counting characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from html.parser import HTMLParser | |
from django.core.validators import MinLengthValidator | |
# via http://stackoverflow.com/a/925630/2295891 (see there for Py2 version) | |
class MLStripper(HTMLParser): | |
def __init__(self): | |
super(MLStripper, self).__init__() | |
self.reset() | |
self.strict = False | |
self.convert_charrefs = True | |
self.fed = [] | |
def handle_data(self, d): | |
self.fed.append(d) | |
def get_data(self): | |
return ''.join(self.fed) | |
def strip_tags(html): | |
s = MLStripper() | |
s.feed(html) | |
return s.get_data() | |
class HTMLStrippingMinLengthValidator(MinLengthValidator): | |
clean = lambda self, x: len(strip_tags(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment