tags:

views:

83

answers:

2

Let's say I have a form field for "Name". I want to display an error message if it contains special characters such as $,#,etc. The only acceptable characters should be any alphanumeric, the hyphen "-", and the apostrophe "'". I am not sure how i should search the name for these non-acceptable characters, especially the apostrophe. So in the code it should look like the following:

name = request.POST['name']

if name contains any non-acceptable characters then display error message.

+1  A: 
import re
p = r"^[\w'-]+$"
if re.search(p, name):
    # it's okay
else:
    # display error
Amber
+1  A: 

You can use regular expressions to validate your string, like this:

import re
if re.search(r"^[\w\d'-]+$", name):
    # success

Another way:

if set("#$").intersection(name):
    print "bad chars in the name"
Nick D