jQuery toggleClass example
Toggle class name on click in jQuery
by ti2005
HTML
<input type="text" id="houronly" placeholder="HH:MM AM/PM format">
JavaScript
function replaceBadInputs(val) {
val = val.replace(/[^\dh: ][AaPp][Mm]/, "");
val = val.replace(/^[^0-1]/, "");
val = val.replace(/^([2-9])[4-9]/, "$1");
if (val.length == 2 && (val === "00" || val > 12)) val = val.slice(0, 1);
val = val.replace(/^\d[:h]/, "");
val = val.replace(/^([01][0-9])[^:h]/, "$1");
val = val.replace(/^(2[0-3])[^:h]/, "$1");
val = val.replace(/^(\d{2}[:h])[^0-5]/, "$1");
val = val.replace(/^(\d{2}h)./, "$1");
val = val.replace(/^(\d{2}:[0-5])[^0-9]/, "$1");
val = val.replace(/^(\d{2}:\d[0-9])[^ ]/, "$1");
val = val.replace(/^(\d{2}:\d{2}[ ])[^AaPp]/, "$1");
val = val.replace(/^(\d{2}:\d{2}[ ][AaPp])[^Mm]/, "$1");
val = val.replace(/^(\d{2}:\d{2}[ ][AaPp][Mm])./, "$1");
if (val && val.length === 8) {
var __ = val.substr(6, 1);
val = __ === "A" || __ === "P" ? val.toUpperCase() : val.toLowerCase();
}
return val;
}
// Apply input rules as the user types or pastes input
document.getElementById('houronly').addEventListener('keyup', function () {
var val = this.value;
var lastLength;
do {
// Loop over the input to apply rules repeately to pasted inputs
lastLength = val.length;
val = replaceBadInputs(val);
} while (val.length > 0 && lastLength !== val.length);
this.value = val;
});
// Check the final result when the input has lost focus
document.getElementById('houronly').addEventListener('blur', function () {
var val = this.value;
val = (/\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))$/.test(val) ? val : "");
this.value = val;
});