The Python Oracle

Optional but not empty field in WTForms

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 Question
01:50 Accepted answer (Score 6)
02:41 Thank you

--

Full question
https://stackoverflow.com/questions/4463...

Question links:
[docs]: http://wtforms.readthedocs.io/en/latest/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #validation #wtforms

#avk47



ACCEPTED ANSWER

Score 6


I took a look at the source of the Optional validator:

class Optional(object):
    ...
    def __call__(self, form, field):
        if not field.raw_data or isinstance(field.raw_data[0], string_types) and not self.string_check(field.raw_data[0]):
            field.errors[:] = []
            raise StopValidation()

As you can see in and not self.string_check(field.raw_data[0]), empty strings are explicitly considered here. I wonder what would happen if I sent two values like a=foo&a=&b=bar.

Anyway, the quick solution for me was to implement a new validator:

class OptionalButNotEmpty(object):
    """
    Allows missing but not empty input and stops the validation chain from continuing.
    """
    # Code is a modified version of `Optional` (https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py#L148)
    field_flags = ('optional', )

    def __call__(self, form, field):
        if not field.raw_data:
            raise wtforms.validators.StopValidation()