If you are using a UI framework, refer to their documentation they would probably have a plugin to do it for you. Or if you want to do it on your own:
From the HTML side you can use type="time"
attribute (please check the browser support for this).
And from JavaScript you can use something like ^([01]\d|2[0-3]):?([0-5]\d)$
on form submission for example.
const TIME_REGEX = /([01]\d|2[0-3]):?([0-5]\d)$/;
const myTimeElm = document.getElementById('myTime');
const outputElm = document.getElementById('output');
let timer;
outputElm.addEventListener('click', () => {
if (TIME_REGEX.test(myTimeElm.value)) {
outputElm.innerText = myTimeElm.value;
} else {
outputElm.innerText = "Error!"
}
});
#output {
cursor: pointer;
}
<input type="time" id="myTime" value="00:00">
<span id="output">click here!</span>
If you don't want to use HTML's type="time", consider using a mask for your input where you record the user's input and render the formatted output in a different component.
Since using the RegEx alone won't achieve the same user experience as you may want to workout the input's cursor position.
Or simple use a library that does that for you (Cleave.js for example)