codice:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Esempio</title>
<script type="text/javascript">
function checkTime (oToCheck, oPssEvt1) {
var oKeyEvent = oPssEvt1 || window.event || { charCode: 0, keyCode: 0 },
nChar = oKeyEvent.charCode,
nKey = oKeyEvent.keyCode,
sVal = oToCheck.value,
sNewVal = sVal.substring(0, oToCheck.selectionStart - (nKey === 8 && nChar === 0 ? 1 : 0)) + (nChar > 0 ? String.fromCharCode(nChar) : "") + sVal.slice(oToCheck.selectionEnd + (nKey === 46 && nChar === 0 ? 1 : 0)), bFormat = nChar === 0 || /^\d{1,2}(?:\:\d{1,2})?$/.test(sNewVal);
if (bFormat) {
var bCorrect = sNewVal.split(":");
for (var nDigit = 0; nDigit < bCorrect.length; nDigit++) {
if (parseFloat(bCorrect[nDigit]) > 59) {
bFormat = false; break;
}
}
}
return bFormat;
}
function formatTime (oToFix, oPssEvt2) {
var nKey = (oPssEvt2 || window.event || { keyCode: 8 }).keyCode, nSelS = oToFix.selectionStart, nSelE = oToFix.selectionEnd, sVal = oToFix.value;
if (nSelS === nSelE && nSelS === sVal.length && /^\d{1,2}$/.test(sVal) && parseFloat(sVal) > 5 && nKey !== 8 && nKey !== 46 && (nKey < 32 || nKey > 41)) {
sVal += ":";
oToFix.value = sVal.replace(/^(\d)\:/, "0$1:");
oToFix.focus();
} else if (/\:\d$/.test(sVal) && parseFloat(/\d$/.exec(sVal)) > 5) {
oToFix.value = sVal.replace(/\d$/, "0$&");
oToFix.focus();
}
}
</script>
</head>
<body>
<form name="myForm">
<input type="text" name="myInput" onkeypress="return checkTime(this,event);" onkeyup="formatTime(this,event);" onpaste="return false;" /></p>
</form>
</body>
</html>