Validar hora mientras se va escribiendo.
JavaScript
1.357 visualizaciones desde el 11 de Marzo del 2020
Un simple input para hora de tipo 24hrs que es validado y formateado mientras se escribe.





(2)














Hora: <input type="text" class="hora" size="5" autofocus />
<script>
document.querySelector('.hora').addEventListener('keypress',validateHour);
document.querySelector('.hora').addEventListener('blur',formatHour);
function validateHour( e )
{e.preventDefault( );
if ( !isNaN(e.key) || e.key==':' )
{var position = this.selectionStart;
var text = this.value;
var textStart = text.substr(0,position);
var textEnd = text.substr(this.selectionEnd);
var textNew;
if ( e.key != ':' || ( e.key == ':' && (textStart+textEnd).search(':') == -1 ) )
{textNew = textStart + e.key + textEnd;
if ( textNew.search(':') != -1 )
{var aText = textNew.split(':');
textStart = aText[0];
textEnd = aText[1];
if( textStart<24 && textEnd<60 )
{if ( e.key == ':' && textStart.length < 2 )
{if ( textStart.length == 0 )
{position++;
}textStart = textStart.padStart(2, '0');
position++;
}textNew = textStart + ':' + textEnd;
}else
{return;
} }else
{switch( textNew.length )
{ case 1:break;
case 2:if ( textNew >= 24 )
{textNew = '00:' + textNew;
position = 4; }else if ( e.key == ':' )
{textNew = textNew + ':';
position++;
}break;
case 3:if ( textNew.substr(0, 2) < 24 && textNew.substr(2, 1) < 60 )
{textNew = textNew.substr(0, 2) + ':' + textNew.substr(2, 1);
}else if ( textNew.substr(0, 1) < 24 && textNew.substr(1, 2) < 60 )
{textNew = textNew.substr(0, 1).padStart(2, '0') + ':' + textNew.substr(2, 1);
}else
{return;
}position++;
break;
case 4:if ( textNew.substr(0, 2) < 24 && textNew.substr(2, 2) < 60 )
{textNew = textNew.substr(0, 2) + ':' + textNew.substr(2, 2);
position++;
}else
{return;
}break;
default:return false;
} }if ( textNew.length <= 5 )
{this.value = textNew;
this.selectionStart = ++position;
this.selectionEnd = this.selectionStart;
} } } }function formatHour()
{var text = this.value;
if ( text != "" )
{textPart = text.split(':');
if ( textPart.length == 2 )
{textPart[0] = textPart[0].padStart(2, '0');
textPart[1] = textPart[1].padStart(2, '0');
}else
{switch ( text.length )
{ case 1: case 2:textPart[0] = 0;
textPart.push(text);
break;
case 3:if ( text.substr(0, 1)<24 && text.substr(1, 2)<60 )
{textPart[0] = text.substr(0, 1);
textPart.push(text.substr(1, 2));
}else if ( text.substr(0, 2)<24 && text.substr(2, 1)<60 )
{textPart[0] = text.substr(0, 2);
textPart.push(text.substr(2, 1));
}break;
case 4:textPart[0] = text.substr(0, 2);
textPart.push(text.substr(2, 2));
break;
} }if ( textPart.length == 2 )
{textPart[0] = String(textPart[0]).padStart(2, '0');
textPart[1] = String(textPart[1]).padStart(2, '0');
this.value = textPart.join(':');
}else
{this.value = '';
} } }</script>
Comentarios sobre la versión: 0.1 (2)
una opción adaptable al script:
{}P.D.: No he revisado detenidamente, ni probado el código.
Espero sea útil.