How can I check the form entry for special characters in python?

Let's say I have a form field for "Name". I want to display an error message if it contains special characters like $, #, etc. The only valid characters are any alphanumeric characters, the hyphen "-" and the apostrophe "". I'm not sure how I should be looking for a name for these inappropriate characters, especially the apostrophe. Therefore, in the code, it should look like this:

name = request.POST ['name']

if the name contains any unacceptable characters then an error message is displayed.

+2


source to share


2 answers


You can use regular expressions to validate your string, for example:

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

      



Another way:

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

      

+3


source


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

      



+1


source







All Articles