In WTForms, can I create a custom validator based on data from a database?
For example, I want to show a multiselect field where users can only choose a certain number of values based on their account type (stored in DB).
The intended behavior is this:
Is this possible?
You can write a custom validator to do anything you can do in python:
user = # get user from request context
def account_type_check(form, field):
account = get_account_for_user(user) # insert your account retrieval logic here
if len(field.data) > account.user_limit:
raise ValidationError('Submission exceeded user's account type limit')
class SelectionForm(Form):
selection = MultiSelectField('Selection', [account_type_check])
Its worth noting that you are arguably using an ill purposed tool for this sort of thing. The purpose of a form validation library is to provide a DRY approach to validating form submissions. This works well for testing length of strings, that numbers are within range, etc. Once the validation scenarios become sufficiently complex you spend more time trying to make the library satisfy your need than it would take to write the validation yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With