通知用户 Dash 中的无效输入

Inform user of invalid input in Dash

我使用破折号创建了一个仪表板。它有一个输入框,用户可以在其中输入一些数据。如果在附加的数据框中找到数据,则会显示一些图表。但是,如果在数据框中找不到用户输入的内容,则什么也不会发生,页面将保持空白。如果输入无效,是否可以显示错误消息:

dash-core-componentInput 组件有一个 pattern 属性 你可以使用:

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.

现在,如果您只想验证字符串的格式,您可以将一些正则表达式模式传递给 pattern 属性。

如果您想根据是否在数据框中找到输入值进行验证,您可以这样做:

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

这里的想法是根据输入值过滤数据框。如果在数据框中找不到输入值,我们想让模式无效。

我在这里的做法是使模式值等于与另一个值连接的输入值,以确保模式不匹配。

如果输入值与数据框中的数据匹配,则模式设置为等于输入值。