Skip to content

Instantly share code, notes, and snippets.

@mathiasose
Last active August 29, 2015 14:10
Show Gist options
  • Save mathiasose/6f680c40090155d41342 to your computer and use it in GitHub Desktop.
Save mathiasose/6f680c40090155d41342 to your computer and use it in GitHub Desktop.
Django MinLengthValidator that ignores HTML tags when counting 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