Check input before continuing - st.text_input()

input_postcode = st.text_input("Postcode : ")

how would we do if we wanted to check if the length is 6 and in a list?

If the condition is not met, we will not proceed.

Thanks.

1 Like

Hi Andrew,

I think the simplest way to build what you are asking for is to use simple if-else statements like this:

import streamlit as st

accepted_postcodes = ['111111', '222222', '333333']

input_postcode = st.text_input("Postcode")

if len(input_postcode) > 0:
    if len(input_postcode) != 6 or input_postcode not in accepted_postcodes:
        st.error("Invalid postcode")
    else:
        st.write("Here goes the rest of the app")

Be aware though, that this may be unsustainable for an app with more advanced logic.

What I think is a better choice for you as your postcodes sound like they are a predefined list, is to use Streamlit’s built in selectbox widget, e.g.:

import streamlit as st

postcodes = ['111111', '222222', '333333']

input_postcode = st.selectbox("Select a postcode", ["-"] + postcodes) # Added a dummy option '-'

if input_postcode != "-":
    st.write("Do stuff here")

Whether or not you want to include a ‘dummy option’ like “-” is of course up to you!

Hope it helps.

Best regards,
Peter

1 Like

I’m actually sending the postcode info to an array = [‘postcode’,‘distance’] and it will be sent to a model.predict([array])

It’s working at my end so I just want to add the check as mentioned to ensure that users didn’t input single digit.

I think based on the if-else , it should work.

thanks