Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wtforms validating dropdown values

Tags:

I'm putting together a form using Flask & WTForms, however, when it comes to dropdowns I want to have a 'please select' option for each dropdown, upon selected causes validation required to be false, e.g. a value hasn't yet been selected.

Do I need to use regex validation or custom validation to achieve this? If I do need custom validation, then how do I go about constructing one?

CAR_MAKES = [('-1', "Please select a vehicle make..."), (1, 'Honda'),
(2, 'Ford'), (3, 'BMW')]
dd_car_makes = SelectField('dd_car_makes', choices=CAR_MAKES,
validators=[DataRequired()])
like image 246
FlipflopPancake Avatar asked Feb 01 '17 08:02

FlipflopPancake


1 Answers

You can use a custom validator here. Have a look at Custom Validators in the WTForms Documentation.

def your_validator(form, field):
    if field.data == -1:
        raise ValidationError('Please select a vehicle make...')

dd_car_makes = SelectField('dd_car_makes', choices=CAR_MAKES,
                            validators=[DataRequired(), your_validator])
like image 192
MrLeeh Avatar answered Sep 22 '22 22:09

MrLeeh