0

I have constructed a wxTextCtrl and want to return true if ONLY digits are entered by the user.

Here is my Python code:

@staticmethod    
def isAllDigits(s):

    for char in list(s):
        if not char.isdigit():
            return False
        else:
            break
    return True 

And my code that calls isAllDigits:

     if self.firstNum.IsEmpty() or not self.isAllDigits(self.firstNum.GetValue()):
        self.dataInputIsValid = False 
        msgStr = "Your first number is invalid, please enter only enter digits and do not leave the field blank."
        wx.MessageBox(msgStr)

    if self.secondNum.IsEmpty() or not self.isAllDigits(self.secondNum.GetValue()):
        self.dataInputIsValid = False 
        msgStr = "Your second number is invalid, please enter only enter digits and do not leave the field blank."
        wx.MessageBox(msgStr)

For some reason my isAllDigits method is not detecting only digits. For example, If I were to enter "3k5" into the textCtrl, my program returns that "3k5" is all digits and is valid, which is incorrect.

What is wrong with my isAllDigits method?

Philip McQuitty
  • 1,077
  • 9
  • 25
  • 36

2 Answers2

1

You can do this way

@staticmethod    
def isAllDigits(s):
    s=s.split('.')
    if len(s)>2:
       return false

    return all( s.isdigit() for char in s)

or in your method Remove else .. break part

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0

This try ... except worked for me on pyqt4 Qlineedit

def textBoxNumbersOnly(QlineEdit):
    if QlineEdit.text()!="-" and QlineEdit.text()!="+":
        try:
            float(QlineEdit.text())
        except ValueError:
            QlineEdit.setText(QlineEdit.text()[:-1])
            QlineEdit.setCursorPosition = len(QlineEdit.text())
    pass

It does not throw an exception if you start with '-' or '+'. It allows floats; does not allow mistakes such as '3.14.14'. It omits the wrong character and moves the cursor to the end of the line. You may need to tweak it to work for your application.