The Python Oracle

Optional but not empty field in WTForms

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life

--

Chapters
00:00 Optional But Not Empty Field In Wtforms
01:27 Accepted Answer Score 6
02:02 Thank you

--

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

--

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()