Login

Safing HTML Text Input

Author:
PizzaPanther
Posted:
December 16, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Personally I hate using markdown for text input just so it can be converted into HTML. Markdown languages almost always don't support some thing I want to do; thus, why not just use HTML in the first place. Well because you don't want anybody posting any kind of HTML on your site.

Solution, instead of making your users learn markdown, let them enter HTML and filter out bad tags. This is a filter I use to filter HTML for only certain allowed tags. The allowed tags can be configured with the allowedhtml list.

To make your text input even more user friendly use a Javascript HTML editor like FCK Editor so your users will have a nice GUI editor.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import re

@register.filter
def forumFormat (value):
  allowedhtml = ['br', 'strong', 'b', 'p', 'div', 'em', 'u', 'strike', 'ul', 'li', 'ol', 'a', 'img', 'highlight', 'sup', 'sub', 'span', 'big', 'small', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'pre', 'address', 'code', 'kbd', 'samp', 'var', 'del', 'ins', 'cite', 'q', 'bdo']
  ret = ""
  ok = False
  closed = True
  
  for i in range(0, len(value)):
    c = value[i:i + 1]
    if c == '<':
      if closed:
        ok = False
        for a in allowedhtml:
          if re.search("^\s*" + a, value[i + 1:], re.I) or re.search("^/\s*" + a, value[i + 1:], re.I):
            ok = True
            closed = False
            break
            
        if not ok:
          c = "&lt;"
          
      else:
        c = "&lt;"
        
    elif c == ">":
      if ok:
        ok = False
        closed = True
        
      else:
        c = "&gt;"
        
    ret += c
    
  return ret
  

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.