Question

How can I write a custom validator which is always executed, even when the user has submitted an empty or missing value?

I've tried overriding the to_python, validate_python, _to_python, _validate_python (and more) methods but none of these seem to get run if the user has submitted an empty or None value

Was it helpful?

Solution 2

I ended up moving from FormEncode to WTForms and everything is now a whole lot easier. Seems to me like Formencode wasn't very well thought out.

OTHER TIPS

I found I was able to do it with a prevalidator but I'm not sure if it's the best way. The problem with doing it this way is that nothing else gets validated if the captcha fails. I can use chained_validators instead of pre_validators but that has the inverse effect where the captcha is only validated if all other fields pass.

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'})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top