Search code examples
pythonstringalphanumeric

If userinput String is empty or numeric or has non ascii-Python


When the user enters the first name and if it is blank or has digit or alphanumeric or has non ascii chars I am not going to insert it into database.

With this code below it does not accept valid input, it works only if I use len and isDigit those 2 conditions.

while (len(f_name) == 0  or f_name.isdigit()

or

f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
Create new user: Y/N ?y
Enter first name: ui
First name cannot be empty or have numeric values

Can someone please explain how to fix this issue? Thanks for your time. Rest of the code is below:

import sqlite3

#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')

#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()

#This function to check if table exists
def create_Table():
    #Check if the table exists or not
    crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
    tableSize=len(crsr.fetchall())#will be greater than 0 if table exists
    if tableSize>0:
        print()
    else:
        #create the table
        crsr.execute(""" Create Table phonebook(
                    FirstName text NOT NULL,
                    LastName text,
                    Phone text PRIMARY KEY NOT NULL)
                   """)

        #check if table got created or not
        crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
        tableSize = len(crsr.fetchall())  # will be greater than 0 if table exists
        if tableSize > 0:
            print('Table was created successfully')

#This function will create new users and insert in DB
def create_User():
    try:
        while True:
            rsp = input('Create new user: Y/N ?')
            if rsp == 'y':
                f_name = input('Enter first name: ')
                # First name cannot be empty or have numeric values
                while (len(f_name) == 0  or f_name.isdigit() or f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
                    print('First name cannot be empty or have numeric values')
                    f_name = input('Enter first name: ')
                l_name = input('Enter last name: ')
                phone = input('Enter phone number: ')
                crsr.execute("INSERT INTO phonebook VALUES (:FirstName, :LastName, :Phone)",
                             {'FirstName': f_name, 'LastName': l_name, 'Phone': phone})
                conn.commit()
            if rsp == 'n':
                break
    except:
     print('UNIQUE constraint failed: phone number already exists')

Solution

  • If you are comfortable with regular expressions, you can test for the conditions "must not be empty" and "must not contain digits" in the following way:

    import re
    
    # match one or more characters that range from a to z or A to Z
    username_check = re.compile(r'[a-zA-Z]+')
    
    ...
    while True:
      if rsp == 'y':
        f_name = input('Enter first name: ')
        while not username_check.fullmatch(f_name):
          print('First name cannot be empty or have numeric values')
          f_name = input('Enter first name: ')
    

    The nice thing about regular expressions is that you can extend the current minimal solution quite flexibly to test for very specific patterns as well:

    import re
    
    # allow unicode word characters
    allowed = re.compile(r'\w+')
    # numbers are still not allowed
    forbidden = re.compile(r'\d')
    
    while True:
        f_name = input('Enter first name: ')
        while not (allowed.fullmatch(f_name) and not forbidden.search(f_name)):
          print('First name cannot be empty or have numeric values')
          f_name = input('Enter first name: ')