Frage

Wie Validate Worte geteilt durch ein Komma von FormEncode?

So etwas wie folgt aus:

"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]
War es hilfreich?

Lösung

Sie werden wahrscheinlich brauchen einen benutzerdefinierten Validator . Hier ist ein kleines Beispiel:

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)

Natürlich, werden Sie wollen Validierung speziell für Ihren Anwendungsfall hinzuzufügen.

Andere Tipps

Unter der Annahme, jedes Wort wird durch ein Komma und ein Leerzeichen (', ') getrennt:

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

Und dann diese Liste weitergeben zu FormEncode und hat es tun, was Sie brauchen, es zu tun.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top