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
|
# Copyright (C) 2007-2008 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
from formencode.validators import *
from formencode.compound import *
from formencode.api import Invalid, NoDefault
from formencode.schema import Schema
from formencode import ForEach
def _(s): return s # dummy
class UniqueList(FancyValidator):
"""
Given a list, ensure that all of the values in it are unique.
>>> x = UniqueList()
>>> x.validate_python(['1','1'],'')
Traceback (most recent call last):
...
formencode.api.Invalid: Duplicate values are not allowed
>>> x.validate_python(['1','2'],'')
>>>
"""
not_empty = None
messages = {
'notunique': _('Duplicate values are not allowed'),
'empty': _('Empty values not allowed'),
}
def __initargs__(self, new_attrs):
if self.not_empty is None:
self.not_empty = True
def validate_python(self, value, state):
if not isinstance(value, list):
return # just punt for now
if self.not_empty:
for v in value:
if v is None or len(v) == 0:
raise Invalid(self.message('empty', state),
value, state)
orig = len(value)
check = len(set(value))
if orig > check:
raise Invalid(self.message('notunique', state),
value, state)
|