Make input fields required* using st.form

When using streamlit form with many input fields or selectbox, how can I make a field as required ?

1 Like

Hi @Neo,

Thanks for posting! You could add an if statement to your code that executes if the submit button has been clicked and checks whether an input widget has been completed. If it hasn’t been completed, you can display a message telling the user to complete it. You should also set clear_on_submit to false so that the form doesn’t reset after being submitted, to account for the case in which the user needs to go back and fill in the required fields.

This feature would be really helpful… not allowing the user to leave a field until a valid input was made for a required field would be way better than issuing an error when they submit.
This should be an option for any field, not just ones on forms.
the on_change= function could be used - if it returns False, don’t let the user move to the next field or navigate away…

While what you suggest does work, this still is not an ideal case for the following reason: if a form is submitted with all necessary fields populated, ideally I would want the form to be cleared upon submission and hence would want clear_on_submit set to True. When, however, a necessary field is left empty I would indeed want the already populated fields to retain the provided input rather than being cleared.

I could not make things work with a form but wrote a workaround that does not use a form as follows: I created input fields (not inside a form), created state vars assigned to keys of input fields, added a standard button, created a function to reset the state variables to be called from within the on_click function of the button only when all compulsory fields are populated.

However, I do think this is way too much work for a simple form validation, which is pretty fundamental feature built into any web framework that I’ve ever worked with (I do recognise that Streamlit probably does not aim to become an all-purpose web framework but still), and in my humble opinion, make it difficult for Streamlit to be adopted by a wider user base.

1 Like

Hey @bararan,

I’d recommend sharing this request as a formal feature enhancement request here so our engineering and product teams can take a look!

1 Like

Hi @Caroline,

Thanks a lot for the recommendation. I will submit a request at the link you provided.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.