If you are utilizing a user interface framework, it's recommended to consult their documentation as they may have a plugin available for this task. Alternatively, if you prefer to tackle it yourself:
On the HTML side, you can make use of the type="time"
attribute (be sure to check for browser support).
In JavaScript, you could implement 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 the HTML's type="time" isn't suitable, you could consider using a mask for your input to capture the user's input and display the formatted result in a separate component.
Solely relying on RegEx might not deliver the desired user experience, especially when considering the manipulation of the input cursor position.
Alternatively, you can opt for a library that handles this functionality for you (Cleave.js, for instance).