3
votes

What I am basically looking for is the RadioField equivalent validator for InputRequired() for WTForms. What I am mean is when you try to submit a form without entering any text into a StringField field that has the InputRequired() validator, The user gets a prompt above the text field saying "Please fill out this field". I want the User to have to pick either male or female.

This is easily done in HTML forms by just including the required attribute in your HTML form. But I cannot seem to understand what the equivalent is in WTForms for RadioField. InputRequired() and DataRequired() are both just for Input text fields and don't seem to work with any other type of fields.

If I have the below very simple WTForms class for signup form, InputRequired() works great in this instance as it gives the user the prompt "Please fill out this field" If they forget to either put in their name or surname. The form will not submit unless they give input into these fields.

class Signup(FlaskForm):
name = StringField('First Name', validators=[InputRequired()])
surname = StringField('Last Name', validators=[InputRequired()])
submit = SubmitField('Signup')

But if I have the below form that has a RadioField, What is the equivalent validator to force the User to pick Male or Female and if they do not pick one I want to give the prompt "please fill out this field"? (I am using BootStrap) I cannot seem to find any information about it. Does it exist? This question here in the second answer basically had what I am looking for Required="Required" but that has since been made obsolete since June 2018. I have tried pretty much every approach with trying to use InputRequired() or DataRequired() with RadioField but no success.

class StudentPersonalQs(FlaskForm):
gender = RadioField('Gender', choices = [('Male','Male'),('Female','Female')])
age = SelectField('Age', choices = [('12', '12'), ('13', '14'),('15', '15'), ('16', '16'),('17', '17'), ('18+', '18+')])
submit = SubmitField('Signup')
1

1 Answers

0
votes

IMO, you can only use this way to achieve this currently:

{% for subfield in form.age %}
    <tr>
        <td>{{ subfield(required="required") }}</td>
        <td>{{ subfield.label }}</td>
    </tr>
{% endfor %}