我有一個地圖,說一個字符串映射到像一個函數:發送函數指針與它的參數,然後添加額外的參數,同時調用
validator = {'first_name' : validate_str,
'last_name' : validate_str,
'phone' : validate_phone }
我需要根據類型調用相應的驗證功能我在地圖上的價值,這些價值將作爲例如我的輸入提供給我
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
除非這種情況下,我不知道這是否可以做到這工作得很好:
的validate_str還檢查給定的字符串是所需的最大長度。
def validate_str(str, max-len):
# Throw error if len(str) > max-len
最大-LEN會有所不同基於字符串,所以我需要調用validate_str爲FIRST_NAME有說64個字符,並與256個字符的姓氏。
我可以使用一個不同的地圖來說這個字段有這個max_len,但是驗證器映射有可能指向帶有根據字段預設的max-len參數的validate_str函數嗎?
類似:
validator = {'first_name' : validate_str(max-len=64),
'last_name' : validate_str(max-len=256),
'phone' : validate_phone }
然後調用它進行驗證,如:
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.
這使生活更輕鬆,使我們不必再記住再次哪些領域將有MAX-LEN一起發送用它。
可能的拼寫錯誤:通過'validate'你的意思'validator'?什麼是「元素」?它似乎是一個像「first_name」,「last_name」或字典這樣的字符串列表。 – ninjagecko 2012-03-02 00:26:37
更正了錯誤..謝謝指出。 – 2012-03-02 00:29:50
沒問題。你可能會從'elements'字典獲得好處'data_name {'first_name':'Bob','last_name':'Bobley','phone':1234567890}'並且在字段data_item() :如果不是驗證器[field](value):...'。閱讀更乾淨。 – ninjagecko 2012-03-02 00:35:38