-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidators.py
executable file
·3295 lines (2879 loc) · 107 KB
/
validators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <[email protected]>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE
"""
import os
import re
import datetime
import time
import cgi
import urllib
import struct
import decimal
import unicodedata
from cStringIO import StringIO
from utils import simple_hash, web2py_uuid, DIGEST_ALG_BY_SIZE
__all__ = [
'CLEANUP',
'CRYPT',
'IS_ALPHANUMERIC',
'IS_DATE_IN_RANGE',
'IS_DATE',
'IS_DATETIME_IN_RANGE',
'IS_DATETIME',
'IS_DECIMAL_IN_RANGE',
'IS_EMAIL',
'IS_EMPTY_OR',
'IS_EXPR',
'IS_FLOAT_IN_RANGE',
'IS_IMAGE',
'IS_IN_DB',
'IS_IN_SET',
'IS_INT_IN_RANGE',
'IS_IPV4',
'IS_LENGTH',
'IS_LIST_OF',
'IS_LOWER',
'IS_MATCH',
'IS_EQUAL_TO',
'IS_NOT_EMPTY',
'IS_NOT_IN_DB',
'IS_NULL_OR',
'IS_SLUG',
'IS_STRONG',
'IS_TIME',
'IS_UPLOAD_FILENAME',
'IS_UPPER',
'IS_URL',
]
try:
from globals import current
have_current = True
except ImportError:
have_current = False
def translate(text):
if text is None:
return None
elif isinstance(text, (str, unicode)) and have_current:
if hasattr(current, 'T'):
return str(current.T(text))
return str(text)
def options_sorter(x, y):
return (str(x[1]).upper() > str(y[1]).upper() and 1) or -1
class Validator(object):
"""
Root for all validators, mainly for documentation purposes.
Validators are classes used to validate input fields (including forms
generated from database tables).
Here is an example of using a validator with a FORM::
INPUT(_name='a', requires=IS_INT_IN_RANGE(0, 10))
Here is an example of how to require a validator for a table field::
db.define_table('person', SQLField('name'))
db.person.name.requires=IS_NOT_EMPTY()
Validators are always assigned using the requires attribute of a field. A
field can have a single validator or multiple validators. Multiple
validators are made part of a list::
db.person.name.requires=[IS_NOT_EMPTY(), IS_NOT_IN_DB(db, 'person.id')]
Validators are called by the function accepts on a FORM or other HTML
helper object that contains a form. They are always called in the order in
which they are listed.
Built-in validators have constructors that take the optional argument error
message which allows you to change the default error message.
Here is an example of a validator on a database table::
db.person.name.requires=IS_NOT_EMPTY(error_message=T('fill this'))
where we have used the translation operator T to allow for
internationalization.
Notice that default error messages are not translated.
"""
def formatter(self, value):
"""
For some validators returns a formatted version (matching the validator)
of value. Otherwise just returns the value.
"""
return value
def __call__(self, value):
raise NotImplementedError
return (value, None)
class IS_MATCH(Validator):
"""
example::
INPUT(_type='text', _name='name', requires=IS_MATCH('.+'))
the argument of IS_MATCH is a regular expression::
>>> IS_MATCH('.+')('hello')
('hello', None)
>>> IS_MATCH('hell')('hello')
('hello', None)
>>> IS_MATCH('hell.*', strict=False)('hello')
('hello', None)
>>> IS_MATCH('hello')('shello')
('shello', 'invalid expression')
>>> IS_MATCH('hello', search=True)('shello')
('shello', None)
>>> IS_MATCH('hello', search=True, strict=False)('shellox')
('shellox', None)
>>> IS_MATCH('.*hello.*', search=True, strict=False)('shellox')
('shellox', None)
>>> IS_MATCH('.+')('')
('', 'invalid expression')
"""
def __init__(self, expression, error_message='invalid expression',
strict=False, search=False, extract=False):
if strict or not search:
if not expression.startswith('^'):
expression = '^(%s)' % expression
if strict:
if not expression.endswith('$'):
expression = '(%s)$' % expression
self.regex = re.compile(expression)
self.error_message = error_message
self.extract = extract
def __call__(self, value):
match = self.regex.search(value)
if match is not None:
return (self.extract and match.group() or value, None)
return (value, translate(self.error_message))
class IS_EQUAL_TO(Validator):
"""
example::
INPUT(_type='text', _name='password')
INPUT(_type='text', _name='password2',
requires=IS_EQUAL_TO(request.vars.password))
the argument of IS_EQUAL_TO is a string
>>> IS_EQUAL_TO('aaa')('aaa')
('aaa', None)
>>> IS_EQUAL_TO('aaa')('aab')
('aab', 'no match')
"""
def __init__(self, expression, error_message='no match'):
self.expression = expression
self.error_message = error_message
def __call__(self, value):
if value == self.expression:
return (value, None)
return (value, translate(self.error_message))
class IS_EXPR(Validator):
"""
example::
INPUT(_type='text', _name='name',
requires=IS_EXPR('5 < int(value) < 10'))
the argument of IS_EXPR must be python condition::
>>> IS_EXPR('int(value) < 2')('1')
('1', None)
>>> IS_EXPR('int(value) < 2')('2')
('2', 'invalid expression')
"""
def __init__(self, expression, error_message='invalid expression', environment=None):
self.expression = expression
self.error_message = error_message
self.environment = environment or {}
def __call__(self, value):
self.environment.update(value=value)
exec '__ret__=' + self.expression in self.environment
if self.environment['__ret__']:
return (value, None)
return (value, translate(self.error_message))
class IS_LENGTH(Validator):
"""
Checks if length of field's value fits between given boundaries. Works
for both text and file inputs.
Arguments:
maxsize: maximum allowed length / size
minsize: minimum allowed length / size
Examples::
#Check if text string is shorter than 33 characters:
INPUT(_type='text', _name='name', requires=IS_LENGTH(32))
#Check if password string is longer than 5 characters:
INPUT(_type='password', _name='name', requires=IS_LENGTH(minsize=6))
#Check if uploaded file has size between 1KB and 1MB:
INPUT(_type='file', _name='name', requires=IS_LENGTH(1048576, 1024))
>>> IS_LENGTH()('')
('', None)
>>> IS_LENGTH()('1234567890')
('1234567890', None)
>>> IS_LENGTH(maxsize=5, minsize=0)('1234567890') # too long
('1234567890', 'enter from 0 to 5 characters')
>>> IS_LENGTH(maxsize=50, minsize=20)('1234567890') # too short
('1234567890', 'enter from 20 to 50 characters')
"""
def __init__(self, maxsize=255, minsize=0,
error_message='enter from %(min)g to %(max)g characters'):
self.maxsize = maxsize
self.minsize = minsize
self.error_message = error_message
def __call__(self, value):
if value is None:
length = 0
if self.minsize <= length <= self.maxsize:
return (value, None)
elif isinstance(value, cgi.FieldStorage):
if value.file:
value.file.seek(0, os.SEEK_END)
length = value.file.tell()
value.file.seek(0, os.SEEK_SET)
elif hasattr(value, 'value'):
val = value.value
if val:
length = len(val)
else:
length = 0
if self.minsize <= length <= self.maxsize:
return (value, None)
elif isinstance(value, (str, unicode, list)):
if self.minsize <= len(value) <= self.maxsize:
return (value, None)
elif self.minsize <= len(str(value)) <= self.maxsize:
try:
value.decode('utf8')
return (value, None)
except:
pass
return (value, translate(self.error_message)
% dict(min=self.minsize, max=self.maxsize))
class IS_IN_SET(Validator):
"""
example::
INPUT(_type='text', _name='name',
requires=IS_IN_SET(['max', 'john'],zero=''))
the argument of IS_IN_SET must be a list or set
>>> IS_IN_SET(['max', 'john'])('max')
('max', None)
>>> IS_IN_SET(['max', 'john'])('massimo')
('massimo', 'value not allowed')
>>> IS_IN_SET(['max', 'john'], multiple=True)(('max', 'john'))
(('max', 'john'), None)
>>> IS_IN_SET(['max', 'john'], multiple=True)(('bill', 'john'))
(('bill', 'john'), 'value not allowed')
>>> IS_IN_SET(('id1','id2'), ['first label','second label'])('id1') # Traditional way
('id1', None)
>>> IS_IN_SET({'id1':'first label', 'id2':'second label'})('id1')
('id1', None)
>>> import itertools
>>> IS_IN_SET(itertools.chain(['1','3','5'],['2','4','6']))('1')
('1', None)
>>> IS_IN_SET([('id1','first label'), ('id2','second label')])('id1') # Redundant way
('id1', None)
"""
def __init__(
self,
theset,
labels=None,
error_message='value not allowed',
multiple=False,
zero='',
sort=False,
):
self.multiple = multiple
if isinstance(theset, dict):
self.theset = [str(item) for item in theset]
self.labels = theset.values()
elif theset and isinstance(theset, (tuple, list)) \
and isinstance(theset[0], (tuple, list)) and len(theset[0]) == 2:
self.theset = [str(item) for item, label in theset]
self.labels = [str(label) for item, label in theset]
else:
self.theset = [str(item) for item in theset]
self.labels = labels
self.error_message = error_message
self.zero = zero
self.sort = sort
def options(self, zero=True):
if not self.labels:
items = [(k, k) for (i, k) in enumerate(self.theset)]
else:
items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)]
if self.sort:
items.sort(options_sorter)
if zero and not self.zero is None and not self.multiple:
items.insert(0, ('', self.zero))
return items
def __call__(self, value):
if self.multiple:
### if below was values = re.compile("[\w\-:]+").findall(str(value))
if not value:
values = []
elif isinstance(value, (tuple, list)):
values = value
else:
values = [value]
else:
values = [value]
thestrset = [str(x) for x in self.theset]
failures = [x for x in values if not str(x) in thestrset]
if failures and self.theset:
if self.multiple and (value is None or value == ''):
return ([], None)
return (value, translate(self.error_message))
if self.multiple:
if isinstance(self.multiple, (tuple, list)) and \
not self.multiple[0] <= len(values) < self.multiple[1]:
return (values, translate(self.error_message))
return (values, None)
return (value, None)
regex1 = re.compile('\w+\.\w+')
regex2 = re.compile('%\((?P<name>[^\)]+)\)s')
class IS_IN_DB(Validator):
"""
example::
INPUT(_type='text', _name='name',
requires=IS_IN_DB(db, db.mytable.myfield, zero=''))
used for reference fields, rendered as a dropbox
"""
def __init__(
self,
dbset,
field,
label=None,
error_message='valor não existe na base de dados',
orderby=None,
groupby=None,
distinct=None,
cache=None,
multiple=False,
zero='',
sort=False,
_and=None,
):
from dal import Table
if isinstance(field, Table):
field = field._id
if hasattr(dbset, 'define_table'):
self.dbset = dbset()
else:
self.dbset = dbset
(ktable, kfield) = str(field).split('.')
if not label:
label = '%%(%s)s' % kfield
if isinstance(label, str):
if regex1.match(str(label)):
label = '%%(%s)s' % str(label).split('.')[-1]
ks = regex2.findall(label)
if not kfield in ks:
ks += [kfield]
fields = ks
else:
ks = [kfield]
fields = 'all'
self.fields = fields
self.label = label
self.ktable = ktable
self.kfield = kfield
self.ks = ks
self.error_message = error_message
self.theset = None
self.orderby = orderby
self.groupby = groupby
self.distinct = distinct
self.cache = cache
self.multiple = multiple
self.zero = zero
self.sort = sort
self._and = _and
def set_self_id(self, id):
if self._and:
self._and.record_id = id
def build_set(self):
table = self.dbset.db[self.ktable]
if self.fields == 'all':
fields = [f for f in table]
else:
fields = [table[k] for k in self.fields]
if self.dbset.db._dbname != 'gae':
orderby = self.orderby or reduce(lambda a, b: a | b, fields)
groupby = self.groupby
distinct = self.distinct
dd = dict(orderby=orderby, groupby=groupby,
distinct=distinct, cache=self.cache,
cacheable=True)
records = self.dbset(table).select(*fields, **dd)
else:
orderby = self.orderby or \
reduce(lambda a, b: a | b, (
f for f in fields if not f.name == 'id'))
dd = dict(orderby=orderby, cache=self.cache, cacheable=True)
records = self.dbset(table).select(table.ALL, **dd)
self.theset = [str(r[self.kfield]) for r in records]
if isinstance(self.label, str):
self.labels = [self.label % dict(r) for r in records]
else:
self.labels = [self.label(r) for r in records]
def options(self, zero=True):
self.build_set()
items = [(k, self.labels[i]) for (i, k) in enumerate(self.theset)]
if self.sort:
items.sort(options_sorter)
if zero and not self.zero is None and not self.multiple:
items.insert(0, ('', self.zero))
return items
def __call__(self, value):
table = self.dbset.db[self.ktable]
field = table[self.kfield]
if self.multiple:
if self._and:
raise NotImplementedError
if isinstance(value, list):
values = value
elif value:
values = [value]
else:
values = []
if isinstance(self.multiple, (tuple, list)) and \
not self.multiple[0] <= len(values) < self.multiple[1]:
return (values, translate(self.error_message))
if self.theset:
if not [v for v in values if not v in self.theset]:
return (values, None)
else:
from dal import GoogleDatastoreAdapter
def count(values, s=self.dbset, f=field):
return s(f.belongs(map(int, values))).count()
if isinstance(self.dbset.db._adapter, GoogleDatastoreAdapter):
range_ids = range(0, len(values), 30)
total = sum(count(values[i:i + 30]) for i in range_ids)
if total == len(values):
return (values, None)
elif count(values) == len(values):
return (values, None)
elif self.theset:
if str(value) in self.theset:
if self._and:
return self._and(value)
else:
return (value, None)
else:
if self.dbset(field == value).count():
if self._and:
return self._and(value)
else:
return (value, None)
return (value, translate(self.error_message))
class IS_NOT_IN_DB(Validator):
"""
example::
INPUT(_type='text', _name='name', requires=IS_NOT_IN_DB(db, db.table))
makes the field unique
"""
def __init__(
self,
dbset,
field,
error_message='value already in database or empty',
allowed_override=[],
ignore_common_filters=False,
):
from dal import Table
if isinstance(field, Table):
field = field._id
if hasattr(dbset, 'define_table'):
self.dbset = dbset()
else:
self.dbset = dbset
self.field = field
self.error_message = error_message
self.record_id = 0
self.allowed_override = allowed_override
self.ignore_common_filters = ignore_common_filters
def set_self_id(self, id):
self.record_id = id
def __call__(self, value):
if isinstance(value,unicode):
value = value.encode('utf8')
else:
value = str(value)
if not value.strip():
return (value, translate(self.error_message))
if value in self.allowed_override:
return (value, None)
(tablename, fieldname) = str(self.field).split('.')
table = self.dbset.db[tablename]
field = table[fieldname]
rows = self.dbset(field == value, ignore_common_filters=self.ignore_common_filters).select(limitby=(0, 1))
if len(rows) > 0:
if isinstance(self.record_id, dict):
for f in self.record_id:
if str(getattr(rows[0], f)) != str(self.record_id[f]):
return (value, translate(self.error_message))
elif str(rows[0][table._id.name]) != str(self.record_id):
return (value, translate(self.error_message))
return (value, None)
class IS_INT_IN_RANGE(Validator):
"""
Determine that the argument is (or can be represented as) an int,
and that it falls within the specified range. The range is interpreted
in the Pythonic way, so the test is: min <= value < max.
The minimum and maximum limits can be None, meaning no lower or upper limit,
respectively.
example::
INPUT(_type='text', _name='name', requires=IS_INT_IN_RANGE(0, 10))
>>> IS_INT_IN_RANGE(1,5)('4')
(4, None)
>>> IS_INT_IN_RANGE(1,5)(4)
(4, None)
>>> IS_INT_IN_RANGE(1,5)(1)
(1, None)
>>> IS_INT_IN_RANGE(1,5)(5)
(5, 'enter an integer between 1 and 4')
>>> IS_INT_IN_RANGE(1,5)(5)
(5, 'enter an integer between 1 and 4')
>>> IS_INT_IN_RANGE(1,5)(3.5)
(3, 'enter an integer between 1 and 4')
>>> IS_INT_IN_RANGE(None,5)('4')
(4, None)
>>> IS_INT_IN_RANGE(None,5)('6')
(6, 'enter an integer less than or equal to 4')
>>> IS_INT_IN_RANGE(1,None)('4')
(4, None)
>>> IS_INT_IN_RANGE(1,None)('0')
(0, 'enter an integer greater than or equal to 1')
>>> IS_INT_IN_RANGE()(6)
(6, None)
>>> IS_INT_IN_RANGE()('abc')
('abc', 'enter an integer')
"""
def __init__(
self,
minimum=None,
maximum=None,
error_message=None,
):
self.minimum = self.maximum = None
if minimum is None:
if maximum is None:
self.error_message = error_message or 'enter an integer'
else:
self.maximum = int(maximum)
if error_message is None:
error_message = 'enter an integer less than or equal to %(max)g'
self.error_message = translate(
error_message) % dict(max=self.maximum - 1)
elif maximum is None:
self.minimum = int(minimum)
if error_message is None:
error_message = 'enter an integer greater than or equal to %(min)g'
self.error_message = translate(
error_message) % dict(min=self.minimum)
else:
self.minimum = int(minimum)
self.maximum = int(maximum)
if error_message is None:
error_message = 'enter an integer between %(min)g and %(max)g'
self.error_message = translate(error_message) \
% dict(min=self.minimum, max=self.maximum - 1)
def __call__(self, value):
try:
fvalue = float(value)
value = int(value)
if value != fvalue:
return (value, self.error_message)
if self.minimum is None:
if self.maximum is None or value < self.maximum:
return (value, None)
elif self.maximum is None:
if value >= self.minimum:
return (value, None)
elif self.minimum <= value < self.maximum:
return (value, None)
except ValueError:
pass
return (value, self.error_message)
def str2dec(number):
s = str(number)
if not '.' in s:
s += '.00'
else:
s += '0' * (2 - len(s.split('.')[1]))
return s
class IS_FLOAT_IN_RANGE(Validator):
"""
Determine that the argument is (or can be represented as) a float,
and that it falls within the specified inclusive range.
The comparison is made with native arithmetic.
The minimum and maximum limits can be None, meaning no lower or upper limit,
respectively.
example::
INPUT(_type='text', _name='name', requires=IS_FLOAT_IN_RANGE(0, 10))
>>> IS_FLOAT_IN_RANGE(1,5)('4')
(4.0, None)
>>> IS_FLOAT_IN_RANGE(1,5)(4)
(4.0, None)
>>> IS_FLOAT_IN_RANGE(1,5)(1)
(1.0, None)
>>> IS_FLOAT_IN_RANGE(1,5)(5.25)
(5.25, 'enter a number between 1 and 5')
>>> IS_FLOAT_IN_RANGE(1,5)(6.0)
(6.0, 'enter a number between 1 and 5')
>>> IS_FLOAT_IN_RANGE(1,5)(3.5)
(3.5, None)
>>> IS_FLOAT_IN_RANGE(1,None)(3.5)
(3.5, None)
>>> IS_FLOAT_IN_RANGE(None,5)(3.5)
(3.5, None)
>>> IS_FLOAT_IN_RANGE(1,None)(0.5)
(0.5, 'enter a number greater than or equal to 1')
>>> IS_FLOAT_IN_RANGE(None,5)(6.5)
(6.5, 'enter a number less than or equal to 5')
>>> IS_FLOAT_IN_RANGE()(6.5)
(6.5, None)
>>> IS_FLOAT_IN_RANGE()('abc')
('abc', 'enter a number')
"""
def __init__(
self,
minimum=None,
maximum=None,
error_message=None,
dot='.'
):
self.minimum = self.maximum = None
self.dot = dot
if minimum is None:
if maximum is None:
if error_message is None:
error_message = 'enter a number'
else:
self.maximum = float(maximum)
if error_message is None:
error_message = 'enter a number less than or equal to %(max)g'
elif maximum is None:
self.minimum = float(minimum)
if error_message is None:
error_message = 'enter a number greater than or equal to %(min)g'
else:
self.minimum = float(minimum)
self.maximum = float(maximum)
if error_message is None:
error_message = 'enter a number between %(min)g and %(max)g'
self.error_message = translate(error_message) \
% dict(min=self.minimum, max=self.maximum)
def __call__(self, value):
try:
if self.dot == '.':
fvalue = float(value)
else:
fvalue = float(str(value).replace(self.dot, '.'))
if self.minimum is None:
if self.maximum is None or fvalue <= self.maximum:
return (fvalue, None)
elif self.maximum is None:
if fvalue >= self.minimum:
return (fvalue, None)
elif self.minimum <= fvalue <= self.maximum:
return (fvalue, None)
except (ValueError, TypeError):
pass
return (value, self.error_message)
def formatter(self, value):
if value is None:
return None
return str2dec(value).replace('.', self.dot)
class IS_DECIMAL_IN_RANGE(Validator):
"""
Determine that the argument is (or can be represented as) a Python Decimal,
and that it falls within the specified inclusive range.
The comparison is made with Python Decimal arithmetic.
The minimum and maximum limits can be None, meaning no lower or upper limit,
respectively.
example::
INPUT(_type='text', _name='name', requires=IS_DECIMAL_IN_RANGE(0, 10))
>>> IS_DECIMAL_IN_RANGE(1,5)('4')
(Decimal('4'), None)
>>> IS_DECIMAL_IN_RANGE(1,5)(4)
(Decimal('4'), None)
>>> IS_DECIMAL_IN_RANGE(1,5)(1)
(Decimal('1'), None)
>>> IS_DECIMAL_IN_RANGE(1,5)(5.25)
(5.25, 'enter a number between 1 and 5')
>>> IS_DECIMAL_IN_RANGE(5.25,6)(5.25)
(Decimal('5.25'), None)
>>> IS_DECIMAL_IN_RANGE(5.25,6)('5.25')
(Decimal('5.25'), None)
>>> IS_DECIMAL_IN_RANGE(1,5)(6.0)
(6.0, 'enter a number between 1 and 5')
>>> IS_DECIMAL_IN_RANGE(1,5)(3.5)
(Decimal('3.5'), None)
>>> IS_DECIMAL_IN_RANGE(1.5,5.5)(3.5)
(Decimal('3.5'), None)
>>> IS_DECIMAL_IN_RANGE(1.5,5.5)(6.5)
(6.5, 'enter a number between 1.5 and 5.5')
>>> IS_DECIMAL_IN_RANGE(1.5,None)(6.5)
(Decimal('6.5'), None)
>>> IS_DECIMAL_IN_RANGE(1.5,None)(0.5)
(0.5, 'enter a number greater than or equal to 1.5')
>>> IS_DECIMAL_IN_RANGE(None,5.5)(4.5)
(Decimal('4.5'), None)
>>> IS_DECIMAL_IN_RANGE(None,5.5)(6.5)
(6.5, 'enter a number less than or equal to 5.5')
>>> IS_DECIMAL_IN_RANGE()(6.5)
(Decimal('6.5'), None)
>>> IS_DECIMAL_IN_RANGE(0,99)(123.123)
(123.123, 'enter a number between 0 and 99')
>>> IS_DECIMAL_IN_RANGE(0,99)('123.123')
('123.123', 'enter a number between 0 and 99')
>>> IS_DECIMAL_IN_RANGE(0,99)('12.34')
(Decimal('12.34'), None)
>>> IS_DECIMAL_IN_RANGE()('abc')
('abc', 'enter a decimal number')
"""
def __init__(
self,
minimum=None,
maximum=None,
error_message=None,
dot='.'
):
self.minimum = self.maximum = None
self.dot = dot
if minimum is None:
if maximum is None:
if error_message is None:
error_message = 'enter a decimal number'
else:
self.maximum = decimal.Decimal(str(maximum))
if error_message is None:
error_message = 'enter a number less than or equal to %(max)g'
elif maximum is None:
self.minimum = decimal.Decimal(str(minimum))
if error_message is None:
error_message = 'enter a number greater than or equal to %(min)g'
else:
self.minimum = decimal.Decimal(str(minimum))
self.maximum = decimal.Decimal(str(maximum))
if error_message is None:
error_message = 'enter a number between %(min)g and %(max)g'
self.error_message = translate(error_message) \
% dict(min=self.minimum, max=self.maximum)
def __call__(self, value):
try:
if isinstance(value, decimal.Decimal):
v = value
else:
v = decimal.Decimal(str(value).replace(self.dot, '.'))
if self.minimum is None:
if self.maximum is None or v <= self.maximum:
return (v, None)
elif self.maximum is None:
if v >= self.minimum:
return (v, None)
elif self.minimum <= v <= self.maximum:
return (v, None)
except (ValueError, TypeError, decimal.InvalidOperation):
pass
return (value, self.error_message)
def formatter(self, value):
if value is None:
return None
return str2dec(value).replace('.', self.dot)
def is_empty(value, empty_regex=None):
"test empty field"
if isinstance(value, (str, unicode)):
value = value.strip()
if empty_regex is not None and empty_regex.match(value):
value = ''
if value is None or value == '' or value == []:
return (value, True)
return (value, False)
class IS_NOT_EMPTY(Validator):
"""
example::
INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())
>>> IS_NOT_EMPTY()(1)
(1, None)
>>> IS_NOT_EMPTY()(0)
(0, None)
>>> IS_NOT_EMPTY()('x')
('x', None)
>>> IS_NOT_EMPTY()(' x ')
('x', None)
>>> IS_NOT_EMPTY()(None)
(None, 'enter a value')
>>> IS_NOT_EMPTY()('')
('', 'enter a value')
>>> IS_NOT_EMPTY()(' ')
('', 'enter a value')
>>> IS_NOT_EMPTY()(' \\n\\t')
('', 'enter a value')
>>> IS_NOT_EMPTY()([])
([], 'enter a value')
>>> IS_NOT_EMPTY(empty_regex='def')('def')
('', 'enter a value')
>>> IS_NOT_EMPTY(empty_regex='de[fg]')('deg')
('', 'enter a value')
>>> IS_NOT_EMPTY(empty_regex='def')('abc')
('abc', None)
"""
def __init__(self, error_message='enter a value', empty_regex=None):
self.error_message = error_message
if empty_regex is not None:
self.empty_regex = re.compile(empty_regex)
else:
self.empty_regex = None
def __call__(self, value):
value, empty = is_empty(value, empty_regex=self.empty_regex)
if empty:
return (value, translate(self.error_message))
return (value, None)
class IS_ALPHANUMERIC(IS_MATCH):
"""
example::
INPUT(_type='text', _name='name', requires=IS_ALPHANUMERIC())
>>> IS_ALPHANUMERIC()('1')
('1', None)
>>> IS_ALPHANUMERIC()('')
('', None)
>>> IS_ALPHANUMERIC()('A_a')
('A_a', None)
>>> IS_ALPHANUMERIC()('!')
('!', 'enter only letters, numbers, and underscore')
"""
def __init__(self, error_message='enter only letters, numbers, and underscore'):
IS_MATCH.__init__(self, '^[\w]*$', error_message)
class IS_EMAIL(Validator):
"""
Checks if field's value is a valid email address. Can be set to disallow
or force addresses from certain domain(s).
Email regex adapted from
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx,
generally following the RFCs, except that we disallow quoted strings
and permit underscores and leading numerics in subdomain labels
Arguments:
- banned: regex text for disallowed address domains
- forced: regex text for required address domains
Both arguments can also be custom objects with a match(value) method.
Examples::
#Check for valid email address:
INPUT(_type='text', _name='name',
requires=IS_EMAIL())
#Check for valid email address that can't be from a .com domain:
INPUT(_type='text', _name='name',
requires=IS_EMAIL(banned='^.*\.com(|\..*)$'))
#Check for valid email address that must be from a .edu domain:
INPUT(_type='text', _name='name',