This validator handles a case where at least one of several fields must be 
non-blank. 

class IS_NOT_ALL_EMPTY(object): 
"""Class representing a validator requiring at least one non-empty field in 
a set. """ 
def __init__(self, others, 
error_message='Enter a value in at least one field'): 
self.others = others 
self.error_message = error_message 

def __call__(self, value): 
okay = (value, None) 
error = (value, self.error_message) 
# Return okay either the 'value', or one of self.others is not empty. 
values = [] 
values.append(value) 
values.extend(self.others) 
empties = [] 
for v in values: 
unused_v, empty = is_empty(v) 
empties.append(empty) 
# Example empties == [True, True, False] 
# If one False exists, it's valid 
if reduce(lambda x, y: x and y, empties): 
return error 
return okay 

Usage: 

db.define_table('contact', 
Field('name', 'string' 
requires=IS_NOT_ALL_EMPTY([request.vars.organization], 
error_message='Enter a name or an organization'), 
), 
Field('organization', 'string', 
requires=IS_NOT_ALL_EMPTY([request.vars.name], 
error_message='Enter a name or an organization'),
)) 

Cheers, 
Jim Karsten 

Reply via email to