Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms validators.optional: continue validation of empty fields?

I have a problem with WTForms validators.optional() because it stops the validation chain if the field is empty (WTForms docs). This means that the validation does not continue with custom functions, which can result in type errors.

Code example:

class MyForm(form):
    myfield = TextField('My Field', [validators.Optional()])

    def validate_myfield(form, field):
        field.data = unicode(field.data)

Is there any way or workaround to continue the validation chain even if the optional content is empty, maybe using custom validators?

If I am approaching the problem in the wrong way, a hint at the right direction would be helpful!

like image 222
lecodesportif Avatar asked Mar 31 '11 22:03

lecodesportif


People also ask

Which of the following Validator can be used for validating an URL?

A URL can be validated by using the following API: sap/base/security/URLListValidator.

Which of the following validation can be used to compare values of two form fields?

You can compare values across different fields using a record validation rule.

What is WTForms flask?

Flask WTForms is a library that makes form handling easy and structured. It also ensures the effective handling of form rendering, validation, and security. To build forms with this approach, you start by creating a new file in our app directory and name it forms.py. This file will contain all the application forms.


1 Answers

You could just change the order in which your validators are listed. If your custom validators are placed before the optional validator it should provide the desired effect as they're evaluated in order.

like image 118
dagoof Avatar answered Oct 01 '22 09:10

dagoof