Reputation:
I'm building lots of forms in an application with wtforms. I have a need to perform, and present the user with, "form-level" validation errors.
There is no documented/supported way to do this. That is fine.
I know I can override the forms validate method, perform my checks there, and put my additional validation errors on the _errors property of the form.
The problem with this approach is that form._errors also contains all of the field-level validation errors (which also, of course, are accessible via the errors property of each field).
So, I want to have a clean, API consistent way to return only form-level validation errors. I can hack this myself on the _error property, but I'm interested in other solutions to this problem.
How would you do form-level validation in wtforms?
Upvotes: 1
Views: 1860
Reputation: 282
As snakecharmerb said: "Form level validation will be available in wtforms 3 (github commit)"
But currently WTForms 3 not released yet, so I'd recommend you to override validate()
form method with attaching flash
message if your condition was not satisfied. Example below.
from flask import flash
def validate(self):
result = super().validate() # Call to parent class' validate method
valid = this or that # Your testing condition
if not valid: # Attach flash message if your validation fails
flash('Your message', 'form_error')
return result and valid
Upvotes: 0
Reputation: 1457
Ther is workaround in wtforms google group which says:
The easiest way to do this would be to add a validate_foo method for one of the fields to your form defintion, and in that then check the other fields as well. All validators receive the form and the field as arguments.
But I'd rather to use flask flash messages
And I've filled a feature request in wtforms maybe they made the feature happen. :)
Upvotes: 1