`I am working on a date time input inside a web app. The format for date and time is MM/DD/YYYY HH:MM:SS. I have to validate the month, date and year. For example, it should prevent user from entering 13 instead of 12 in the month placeholder.
Below is html code.
<label>Date time:
<input placeholder="__/__/____ __:__:__" data-slots="_">
</label><br>
and the js
<script>
document.addEventListener('DOMContentLoaded', () => {
for (const el of document.querySelectorAll("[placeholder][data-slots]")) {
const pattern = el.getAttribute("placeholder"),
slots = new Set(el.dataset.slots || "_"),
prev = (j => Array.from(pattern, (c, i) => slots.has(c) ? j = i + 1 : j))(0),
first = [...pattern].findIndex(c => slots.has(c)),
accept = new RegExp(el.dataset.accept || "\d", "g"),
clean = (input) => {
input = input.match(accept) || [];
return Array.from(pattern, c =>
input[0] === c || slots.has(c) ? input.shift() || c : c
);
},
format = () => {
const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {
i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));
return i < 0 ? prev[prev.length - 1] : back ? prev[i - 1] || first : i;
});
el.value = clean(el.value).join``;
el.setSelectionRange(i, j);
back = false;
};
let back = false;
el.addEventListener("keydown", (e) => back = e.key === "Backspace");
el.addEventListener("input", format);
el.addEventListener("focus", format);
el.addEventListener("blur", () => el.value === pattern && (el.value = ""));
}
});
</script>
Even if its in jquery, its fine but please no External libraries or plugins.
I have tried to prevent it using prevent.default() for keypress event but have reached nowhere.
I just want the user to be prevented from entering wrong date instead of validating after entered.`
2
Answers
Not sure you wanted this, but you can consider using the datepicker (jQuery + datepicker.js).
add tags:
Html:
jQuery:
Sorry if it’s not what you were looking for
You can do this