Use MutationObserver to constrain dynamically-rendered date inputs
Deploy to LXC / deploy (push) Successful in 1m56s
Validate / validate (push) Successful in 29s

Previous afterNavigate hook missed inputs inside conditional blocks
that appear after user interaction (e.g. the "+ New Expense" form).
Replaced with a MutationObserver on document.body that catches every
<input type="date"> as it's added to the DOM and sets min/max.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-20 16:20:50 +07:00
parent 6d0fb30545
commit e216a393e4
+22 -11
View File
@@ -1,23 +1,34 @@
<script lang="ts">
import '../app.css';
import { afterNavigate } from '$app/navigation';
import { onMount } from 'svelte';
let { children } = $props();
// Constrain date inputs so browsers don't render yyyyyy-mm-dd
function constrainDateInputs() {
document.querySelectorAll<HTMLInputElement>('input[type="date"]').forEach((el) => {
if (!el.hasAttribute('min')) el.setAttribute('min', '1900-01-01');
if (!el.hasAttribute('max')) el.setAttribute('max', '2100-12-31');
});
// Constrain date inputs so browsers don't render yyyyyy-mm-dd.
// Uses a MutationObserver so dynamically-rendered inputs get constrained too.
function constrainEl(el: Element) {
if (!(el instanceof HTMLInputElement)) return;
if (el.type !== 'date') return;
if (!el.hasAttribute('min')) el.setAttribute('min', '1900-01-01');
if (!el.hasAttribute('max')) el.setAttribute('max', '2100-12-31');
}
function constrainRoot(root: ParentNode) {
root.querySelectorAll<HTMLInputElement>('input[type="date"]').forEach(constrainEl);
}
onMount(() => {
constrainDateInputs();
});
afterNavigate(() => {
queueMicrotask(constrainDateInputs);
constrainRoot(document);
const observer = new MutationObserver((mutations) => {
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType !== 1) continue;
constrainEl(node as Element);
if ((node as Element).querySelectorAll) constrainRoot(node as Element);
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
return () => observer.disconnect();
});
</script>