Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tudormunteanu/a8ac710a4987dd289c21d04028fc7c9a to your computer and use it in GitHub Desktop.
Save tudormunteanu/a8ac710a4987dd289c21d04028fc7c9a to your computer and use it in GitHub Desktop.
Dash Callback Example of Splitting Validation from Action
import dash
from dash import html, dcc, Input, Output, State, callback, no_update
import re
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Store(id="repo-url-valid-flag", data=False),
#
dcc.Input(id="repo-url-input", type="text", placeholder="[email protected]:user/repo.git"),
html.Button("Download", id="download-repo-btn"),
html.Div(id="error-message"),
html.Div(id="action-message"),
])
def is_valid_repo_url(url):
pattern = r"^[email protected]:[^/]+/[^/]+\.git$"
return bool(re.match(pattern, url or ""))
@app.callback(
[Output("repo-url-valid-flag", "data"), Output("error-message", "children")],
[Input("download-repo-btn", "n_clicks")],
[State("repo-url-input", "value")],
prevent_initial_call=True,
)
def validate_repo_url(n_clicks, url):
if not n_clicks:
return no_update, no_update
if is_valid_repo_url(url):
return True, ""
else:
return False, "Error: URL must match [email protected]:<user>/<repo>.git"
@app.callback(
Output("action-message", "children"),
[Input("repo-url-valid-flag", "data")],
[State("repo-url-input", "value")],
prevent_initial_call=True,
)
def handle_download(valid, url):
if valid:
return f"Download started for {url}"
return ""
if __name__ == "__main__":
app.run_server(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment