Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms: Custom Validator Based on DB Data?

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:

  1. If form is submitted, check how many values are selected.
  2. Run DB query, get account type.
  3. Check if #1 is less than or equal to #2.
  4. If so, consider it valid.

Is this possible?

like image 678
okoboko Avatar asked Mar 07 '26 14:03

okoboko


1 Answers

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.

like image 98
nsfyn55 Avatar answered Mar 09 '26 07:03

nsfyn55



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!