I have a map which says maps a string to a function like :
validator = {'first_name' : validate_str,
'last_name' : validate_str,
'phone' : validate_phone }
I need to call the corresponding validate function based on the type of value I have in the map that will be fed to me as input for e.g.
for name in elements:
# Validate the value of this name in the input map using the function
# input is the map that has the value for each of these fields
# elements is a list of all fields used to loop through one input at a time
if validator[name]( input[name] ) is False:
# Throw validation error
else:
# Do something else
This works fine unless for this scenario I am not sure if it can be done:
The validate_str also checks if a given string is of desired max length.
def validate_str(str, max-len):
# Throw error if len(str) > max-len
The max-len can differ based on the string, so I need to call validate_str for first_name with say 64 characters and last name with 256 characters.
I can use a different map to say that this field has this max_len, but is it possible for the validator map to have pointer to the validate_str function with the max-len argument preset based on the field?
something like:
validator = {'first_name' : validate_str(max-len=64),
'last_name' : validate_str(max-len=256),
'phone' : validate_phone }
then call it for validation like:
if validator[name]( str=input[name] ) is False:
# The appropriate value for max-len goes with the function call and just the
# str is appended to the argument list while invoking.
This makes life easier so that we need not then remember again what fields will have the max-len sent along with it.
validatedo you meanvalidator? What iselements? It seems to be a list of strings likefirst_name,last_name, or a dictionary.elementsa dictionarydata = {'first_name':'Bob', 'last_name':'Bobley', 'phone':1234567890}and doingfor field,value in data.items(): if not validator[field](value):.... Reads much more cleanly.