Search code examples
pythonuser-inputdashboardplotly-dash

Inform user of invalid input in Dash


I have created a dashboard using dash. It has an input box in which the user enters some data. If the data is found in the attached dataframe then a few graphs are shown. But if the input the user entered is not found in the dataframe then nothing happens and the page stays blank. Is there a way to show an error message as so if the input is invalid:

enter image description here


Solution

  • dash-core-component's Input component has a pattern property you could use:

    A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url, email, or password, otherwise it is ignored. The regular expression language is the same as JavaScript RegExp algorithm, with the 'u' parameter that makes it treat the pattern as a sequence of unicode code points. The pattern is not surrounded by forward slashes.

    Now if you only wanted to validate the format of the string you could pass some regex pattern to the pattern prop.

    If you want to validate based on whether the input value is found in your dataframe you could do something like this:

    df = pd.DataFrame({"data": ["1", "2", "3"]})
    
    app = dash.Dash()
    app.layout = html.Div(
        [dcc.Input(id="input", type="text"), html.Div(id="output")], style={"padding": 10}
    )
    
    
    @app.callback(
        Output("output", "children"),
        Output("input", "pattern"),
        Input("input", "value"),
    )
    def number_render(input_value):
        pattern = input_value
        filtered_df = df[df["data"] == input_value]
    
        if filtered_df.empty:
            pattern = pattern + "_invalid"
    
        return input_value, pattern
    

    The idea here is to filter the dataframe based on the value of the input. If the input value is not found in the dataframe we want to make the pattern invalid.

    The way I did it here was to make the pattern value equal to the input value concatenated with another value to make sure the pattern doesn't match.

    If the input value does match the data in the dataframe the pattern is set equal to the input value.