通知用户Dash中的输入无效

2024-04-29 02:05:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

enter image description here


Tags: 数据方法用户消息内容错误图表仪表板
1条回答
网友
1楼 · 发布于 2024-04-29 02:05:43

dash-core-componentInput组件有一个^{}属性,您可以使用:

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

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

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

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

相关问题 更多 >