I have the following code:
<input class="submit-form-on-change" type="month" name="@Model.DatePickerFormKey" value="@Model.InitialValue?.ToString("yyyy-MM")">
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('user-filter-content').querySelectorAll('.submit-form-on-change').forEach(function (element) {
element.addEventListener('change', function () {
this.form.submit();
});
});
}, false);
</script>
I am able to pick a date via date picker but I would like to be able to also fill the input field using the keyboard.
Now my problem here is that every keystroke triggers the form submit.
Is there any way to check if the value of the input is a full valid date?
So I mean that something like 0202-10
is not possible but 2024-10
or even 1993-10
is.
Ok implemented it like this:
I added a timer/debounce so 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.dataset.submitDelay) || 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
const parts = dateString.split("-");
const year = parseInt(parts[0], 10);
const 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>