Using pattern matching, this is not hard to achieve.
To check that each character matches your requirements
With spaces checking:
if allow_special_char == False:
if not re.match("^[a-zA-Z0-9_ ]*$", gname):
Regular expression refer from http://stackoverflow.com/a/336220/1903116