1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """This module contains TextValidator, which is an input validator for the
16 wxTextCtrl. See the wxPython documentation for wxTextCtrl for more about text
17 validators. Three constants are defined for use in TextValidator: ALPHA_ONLY,
18 DIGIT_ONLY, and FLOAT_ONLY. See the TextValidator class for how these are used.
19 """
20
21
22 __id__ = "$Id: validators.py 2980 2009-04-02 00:14:33Z juhas $"
23
24 ALPHA_ONLY = 1
25 DIGIT_ONLY = 2
26 FLOAT_ONLY = 3
27 import wx
28 import string
29
30 -class TextValidator(wx.PyValidator):
31 """This validator is designed to check text input for wxTextCtrls. (It might
32 have uses in other widgets.) It can validate for letters only, digits only,
33 floats only, and can allow for a negative at the beginning of a digit string
34 or a negative float.
35 """
36
37 - def __init__(self, flag=DIGIT_ONLY, allowNeg=False):
38 """Initialize the validator.
39
40 flag -- DIGIT_ONLY, allow only digits (default)
41 ALPHA_ONLY, allow only letters
42 FLOAT_ONLY, allow only floats
43
44 allowNeg -- Allow a negative sign in front of DIGIT_ONLY, or
45 FLOAT_ONLY text. (default False)
46 """
47 wx.PyValidator.__init__(self)
48 self.flag = flag
49 self.allowNeg = allowNeg
50 self.Bind(wx.EVT_CHAR, self.OnChar)
51
53 return TextValidator(self.flag, self.allowNeg)
54
55 - def Validate(self, win):
56 tc = self.GetWindow()
57 val = tc.GetValue()
58
59 if self.flag == ALPHA_ONLY:
60
61 for x in val:
62 if x not in string.letters:
63 return False
64
65 elif self.flag == DIGIT_ONLY:
66
67
68 if self.allowNeg:
69 if val[0] == '-':
70
71 if len(val) > 1:
72 val = val[1:]
73 else:
74 val = ""
75
76
77 for x in val:
78 if x not in string.digits:
79 return False
80
81 elif self.flag == FLOAT_ONLY:
82 try:
83 x = float(val)
84 if x < 0 and not self.allowNeg:
85 return False
86 except ValueError:
87 return False
88
89 return True
90
91 - def OnChar(self, event):
92 key = event.GetKeyCode()
93
94 if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
95 event.Skip()
96 return
97
98 if self.flag == ALPHA_ONLY and chr(key) in string.letters:
99 event.Skip()
100 return
101
102 if self.flag == DIGIT_ONLY:
103 if chr(key) in string.digits:
104 event.Skip()
105 return
106
107 if self.allowNeg and chr(key) == '-':
108
109 win = self.GetWindow()
110 if win.GetInsertionPoint() == 0 and win.GetValue().count('-') == 0:
111 event.Skip()
112 return
113
114 if self.flag == FLOAT_ONLY:
115 win = self.GetWindow()
116 val = win.GetValue()
117 i = win.GetInsertionPoint()
118 newval = val[:i]+chr(key)+val[i:]
119 try:
120 x = float(newval+"1")
121 if x < 0:
122 if self.allowNeg:
123 event.Skip()
124 return
125 else:
126 event.Skip()
127 return
128
129 except ValueError:
130 pass
131
132 if not wx.Validator_IsSilent():
133 wx.Bell()
134
135
136
137 return
138
139
142
145
146
147