pythonvalidationturbogears2formencode

Formencode OneOf validator with dynamic list to test against


I'm using formencode 1.3.0a1 (and turbogeras 2.3.4) and run into a problem with the validator OneOf.

I want to validate some input according to a list in the Database. Here is my validation schema and the method for getting the list:

from formencode import Schema, validators

def getActiveCodes():
    codes = DBSession.query(SomeObject.code).all()
    codes = [str(x[0]) for x in codes]
    return codes

class itemsEditSchema(Schema):
    code = validators.OneOf(getActiveCodes())
    allow_extra_fields = True

The method "getActiveCodes" is executed just once (I guess during schema init or something like that).

I need it to run every time when I want to check my user input for "code", how can I do that?

Thanks for the help


Solution

  • In the end I worte a FancyValidtor instead of using OneOf, here is my code:

    class codeCheck(FancyValidator):
        def to_python(self, value, state=None):
            if value==None:
                raise Invalid('missing a value', value, state)
            return super(codeCheck,self).to_python(value,state)
    
        def _validate_python(self, value, state):
            codes = DBSession.query(Code).all()
            if value not in codes:
                raise Invalid('wrong code',value, state)
            return value
    
    
    class itemsEditSchema(Schema):
        code = codeCheck ()
        allow_extra_fields = True