如何通过 FormEncode 验证用逗号分隔的单词?
像这样的东西:
"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
如何通过 FormEncode 验证用逗号分隔的单词?
像这样的东西:
"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
您可能需要一个自定义验证器。这是一个简单的例子:
import formencode
class CommaSepList(formencode.validators.FancyValidator):
def _to_python(self, value, state):
return value.split(",")
def validate_python(self, value, state):
for elem in value:
if elem == "":
raise formencode.Invalid("an element of the list is empty", value, state)
>>> CommaSepList.to_python("1,2,3")
['1', '2', '3']
>>> CommaSepList.to_python("1,,")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.5/site-packages/FormEncode-1.2.3dev-py2.5.egg/formencode/api.py", line 416, in to_python
vp(value, state)
File "myValidator.py", line 17, in validate_python
raise formencode.Invalid("an element of the list is empty", value, state)
当然,您需要添加特定于您的用例的验证。
假设每个单词由逗号和空格 ( ', '
) 分隔:
>>> x = "foo1, bar2, foo3"
>>> x.split(', ')
['foo1', 'bar2', 'foo3']
然后将该列表传递给 FormEncode 并让它做任何你需要做的事情。