Validating Phone Number and Email address with Python Using conditional statements and regex

Viewed 40

I have written the code below to validate my email address and phone number. Assuming i have entered a wrong email or phone number the program pops out an error message, but after correcting the input the save button does not perform the intended command of inserting records in the database, i am just clicking it without response. If I write the correct information the first time everything works as intended. May you assist me how best i can rewrite my code so that it checks the email and phone number. Below is the full code. It seems when a user inputs the wrong details then correct them. The else statement won't execute.

from tkinter import *
from tkinter import messagebox
import os
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
import sys
import mysql.connector
from mysql.connector import Error
from datetime import date

import re
 

today = date.today()

py = sys.executable


def isValid(s):
     
    # 1) Begins with 0 
    # 2) Then contains 7 
    # 3) Then contains 8 digits
    Pattern = re.compile("(0)?[7][0-9]{8}")
    return Pattern.match(s)

#creating window
class Add(Tk):
    def __init__(self):
        super().__init__()
        self.maxsize(500,600)
        self.minsize(500,600)
        self.title('Add Query')
        self.iconbitmap(img_resource_path("chegutuicon.ico"))
        self.canvas = Canvas(width=500, height=600, bg='gray')
        self.canvas.pack()
        fname = StringVar()
        lname = StringVar()
        cn = StringVar()
        self.gender = StringVar()
        add = StringVar()
        em = StringVar()
        q = StringVar()
        dtRepo =StringVar()
        dtReso =StringVar()

#verifying input
        def asi():
                try:
                    self.conn = mysql.connector.connect(host='localhost',
                                                        database='complains_database',
                                                        user='ngonex',
                                                        password='2dghd')
                    self.myCursor = self.conn.cursor()
                    first = fname.get()
                    last = lname.get()
                    contact = cn.get()
                    gend = gender.get()
                    address = add.get()
                    email = em.get()
                    querr = q.get()
                    dateRepo = dtRepo.get()
                    dateReso = dtReso.get()
                         
                    regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'     # Make a regular expression for validating an Email. The email should meet the pattern.
           
 
                        
                 
                    
                    if (first=="" ):
                        messagebox.showerror("Missing fields Alert!!","Please enter the First Name of Client.")
                    
                    elif(last==""):
                        messagebox.showerror("Missing Field Alert!!", "Please enter the Last Name of Client.")
                    
                    elif(contact==""):
                        messagebox.showerror("Missing Field Alert!!", "Please enter client's Contact Number.")

                    elif(gend==""):
                        messagebox.showerror("Missing Field Alert!!", "Please select client's Gender.")
                    
                    elif(address==""):
                        messagebox.showerror("Missing Field Alert!!", "Please enter physical address.")
                    
                    elif(querr==""):
                        messagebox.showerror("Missing Field Alert!!", "Please input the query or complain.")
                    
            
                    
                    elif(contact!=""):

                        if (isValid(contact)):pass
                                
                        else :
                            messagebox.showerror("Invalid Mobile Number", "Please enter a valid Mobile Number e.g 0773088800.")                 

                       
                    elif (email==""):    
                        pass                             
            
                    elif (email!=""):
                        if(re.fullmatch(regex, email)):pass

                        else:messagebox.showerror("Invalid Email !!", "Please enter a valid email address!.")
                           
                    
                
                    else:                       
                        
                          
                        self.myCursor.execute("Insert into client(FirstName,LastName,Gender,Address,ContactNumber,EmailAddress,Query,DateReported,DateResolved) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)",[first,last,gend,address,contact,email,querr,dateRepo,dateReso])
                        self.conn.commit()
                        messagebox.showinfo("Done","Query Inserted Successfully")
                        ask = messagebox.askyesno("Confirm","Do you want to add another query?")
                        if ask:
                            self.destroy()
                            os.system('%s %s' % (py, 'Add.py'))
                        else:
                            self.destroy()
                            self.myCursor.close()
                            self.conn.close()
                except Error:
                    messagebox.showerror("Error","Something went wrong check your database connection and configurations")
      
        # label and input box
        Label(self, text='Client Details',bg='gray', fg='white', font=('Courier new', 25, 'bold')).place(x=70,y=50)
        Label(self, text='First Name:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=102)
        Entry(self, textvariable=fname, width=30).place(x=200, y=104)
        Label(self, text='Last Name:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=150)
        Entry(self, textvariable=lname, width=30).place(x=200, y=152)
        Label(self, text='Gender:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=200)        
        gender=StringVar()
        ttk.Combobox(self,font=('Courier new', 10),state='readonly',values=('Male','Female'),textvariable=gender).place(x=200, y=202) 
    
        Label(self, text='Address:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=250)
        Entry(self, textvariable=add, width=30).place(x=200, y=250)
        Label(self, text='Contact Number:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=300)
        Entry(self, textvariable=cn, width=30).place(x=200, y=300)
        Label(self, text='Email Address:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=350)
        Entry(self, textvariable=em, width=30).place(x=200, y=350)
        Label(self, text='Query:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=400)
        Entry(self, textvariable=q, width=30).place(x=200, y=400)
        Label(self, text='Date Reported:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=450)
        DateEntry(self, textvariable=dtRepo,date_pattern='YYYY-MM-DD',maxdate=today, mindate=today).place(x=200, y=450)
        Label(self, text='Date Resolved:', bg='gray', font=('Courier new', 10, 'bold')).place(x=70, y=500)
        Entry(self, textvariable=dtReso, width=30, state="disabled").place(x=200, y=500)

        Button(self, text="Save", bg='blue',fg='white', width=15, command=asi).place(x=230, y=550)

Add().mainloop()
0 Answers
Related