开发者

FormEncode validate: words divided by a comma

How to validate words divided by a comma by FormEncode ?

Something like this:

"foo1, foo2, foo3" -> ["foo1",开发者_Go百科 "foo2", "foo3"]


You'll probably need a custom validator. Here's a quick example:

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)

Of course, you'll want to add validation specific to your use case.


Assuming each word is separated by a comma and a space (', '):

>>> x = "foo1, bar2, foo3"
>>> x.split(', ')
['foo1', 'bar2', 'foo3']

And then pass that list on to FormEncode and have it do whatever you need it to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜