正则表达式未正确验证日期

lee*_*eah 1 python regex validation tkinter

 def chkDay(x, size, part):
     dayre = re.compile('[0-3][0-9]') # day digit 0-9
     if (dayre.match(x)):
         if (len(x) > size):
             return tkMessageBox.showerror("Warning", "This "+ part +" is invalid")
             app.destroy
         else:
             tkMessageBox.showinfo("OK", "Thanks for inserting a valid "+ part)
     else:
         tkMessageBox.showerror("Warning", part + " not entered correctly!")
         root.destroy

#when clicked
chkDay(vDay.get(),31, "Day")

#interface of tkinter
vDay = StringVar()
Entry(root, textvariable=vDay).pack()
Run Code Online (Sandbox Code Playgroud)

问题:

  • 没有验证,我可以在一天超过31天,它仍然显示:好的
  • 当我调用root.destroy时,root(application)不会关闭

Mic*_*las 5

使用正则表达式验证日期很难.您可以使用以下某些模式:http://regexlib.com/DisplayPatterns.aspx?cattabindex = 4&categoryId = 5&AspxAutoDetectCookieSupport = 1

或者来自http://answers.oreilly.com/topic/226-how-to-validate-traditional-date-formats-with-regular-expressions/

请记住,特别难以检查年份是否飞跃,例如2011-02-29日期是否有效?

我认为最好使用专门的函数来解析和验证日期.您可以使用strptime()datetime模块.