Ok implemented it like this (thanks to @fdomn-m ):
I added a timer that even if the date is valid the form will be submitted after a certain time to give the user the possibility to type in the year first and then add a month bigger than 9
<input class="submit-form-on-change-delayed" type="month" name="@Model.DatePickerFormKey" value="@Model.InitialValue?.ToString("yyyy-MM")">
<script>
document.addEventListener('DOMContentLoaded', function () {
let debounceTimer;
const userFilterContent = document.getElementById('user-filter-content');
const delay = parseInt(userFilterContent.getAttribute('data-submit-delay')) || 1000; // Default to 1000 ms if no data-delay
userFilterContent.querySelectorAll('.submit-form-on-change-delayed').forEach(function (element) {
element.addEventListener('change', function () {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (isValidDate(this.value)) {
this.form.submit();
}
}, delay);
});
});
}, false);
// Validates that the input string is a valid date formatted as "yyyy-MM"
function isValidDate(dateString) {
// Parse the date parts to integers
var parts = dateString.split("-");
var year = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
// Check the ranges of month and year
if (year < 1000 || year > 9999 || month == 0 || month > 12)
return false;
return true;
};
</script>