2013-05-13 63 views
0

即使用戶提交了空值或缺失值,我如何編寫始終執行的自定義驗證程序?Formencode和空值

我試圖重寫to_python,validate_python,_to_python,_validate_python(及以上)的方法,但沒有這些似乎如果用戶提交一個空或無值

回答

0

我最終從FormEncode移動到WTForms,現在一切都變得容易多了。對我來說似乎Formencode不是很好的想法。

0

我發現我能夠獲得運行用prevalidator做,但我不確定這是否是最好的方法。這樣做的問題是,如果驗證碼失敗,沒有其他任何驗證。我可以使用chained_validators而不是pre_validators,但是,如果所有其他字段都通過,驗證碼纔會生效。

class LoginForm(formencode.Schema): 
    ... 
    captcha = formencode.validators.String(if_missing=None) 
    pre_validators = [validators.Captcha('captcha')] 



class Captcha(formencode.validators.FormValidator): 

    def __init__(self, captcha_name): 
     self.captcha_name = captcha_name 

    def validate_python(self, value_dict, state): 
     if not captcha.test_captcha(value_dict.get(self.captcha_name)): 
      raise formencode.Invalid('Captcha error', self.captcha_name, state, error_dict={self.captcha_name: 'Captcha did not match'})