Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Add validation for file type extensions in mo.ui.file (#3124)

devin-ai-integration[bot]17ba471690b0
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index 3bc0521f99..289f8899bf 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -1308,6 +1308,18 @@ class file(UIElement[List[Tuple[str, str]], Sequence[FileUploadResults]]):
Callable[[Sequence[FileUploadResults]], None]
] = None,
) -> None:
+ # Validate filetypes have leading dots or contain a forward slash
+ if filetypes is not None:
+ invalid_types = [
+ ft for ft in filetypes if not (ft.startswith(".") or "/" in ft)
+ ]
+ if invalid_types:
+ raise ValueError(
+ f"File types must start with a dot (e.g., '.csv' instead of 'csv') "
+ f"or contain a forward slash (e.g., 'application/json'). "
+ f"Invalid types: {', '.join(invalid_types)}"
+ )
+
super().__init__(
component_name=file._name,
initial_value=[],
diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.py
index 64ed4ee2a3..a02d9ef2c0 100644
--- a/tests/_plugins/ui/_impl/test_input.py
+++ b/tests/_plugins/ui/_impl/test_input.py
@@ -460,7 +460,36 @@ def test_form_in_dictionary_allowed() -> None:
assert checkbox._id != d["form"].element._id
-# TODO(akshayka): test file
+def test_file_validation() -> None:
+ """Test file type validation in the file class."""
+ # Valid filetypes should be accepted
+ ui.file(filetypes=[".csv", ".txt"])
+ ui.file(filetypes=["audio/*"])
+ ui.file(filetypes=["video/*"])
+ ui.file(filetypes=["image/*"])
+ ui.file(filetypes=["application/json"])
+ ui.file(filetypes=["text/plain"])
+ ui.file(filetypes=[".csv", "application/json"]) # Mixed types are allowed
+ ui.file(filetypes=["text/html", "application/xml"]) # Multiple MIME types
+
+ # Invalid filetypes should raise ValueError
+ with pytest.raises(ValueError) as e:
+ ui.file(filetypes=["csv"])
+ assert "must start with a dot" in str(e.value)
+ assert "or contain a forward slash" in str(e.value)
+ assert "csv" in str(e.value)
+
+ with pytest.raises(ValueError) as e:
+ ui.file(filetypes=["txt", ".csv"])
+ assert "must start with a dot" in str(e.value)
+ assert "or contain a forward slash" in str(e.value)
+ assert "txt" in str(e.value)
+
+ with pytest.raises(ValueError) as e:
+ ui.file(filetypes=["doc", "pdf"])
+ assert "must start with a dot" in str(e.value)
+ assert "or contain a forward slash" in str(e.value)
+ assert "doc, pdf" in str(e.value)
@pytest.mark.skipif(not HAS_NUMPY, reason="numpy not installed")