'Allow input of HH:MM:SS into form field only

I want to limit the possible input into an <input> field to only HH:MM:SS. This is meant as a duration rather than 24h time of day (up to a maximum of 99h 59m 59s) I would prefer to do the validation of input as the user is typing rather than at the end.

This is what I've written up so far: https://jsfiddle.net/x41boh5p/

HTML

<input type="text" id="fieldDuration" maxlength="8" placeholder="HH:MM:SS">

JS:

function validateInput(entry){
  if(entry.length==1 || entry.length==2 || entry.length==4 || entry.length==5 || entry.length==7 || entry.length==8){
    if(isNaN(entry.charAt(entry.length - 1))){
        $("#fieldDuration").val(entry.slice(0, -1));
    }
  }else if(entry.length==3 || entry.length==6){
    if(entry.charAt(entry.length - 1) !== ":"){
       $("#fieldDuration").val(entry.slice(0, -1));
    }
   }
}

$("#fieldDuration").keyup(function(){
    entry = $(this).val();
    validateInput(entry);
});

While this works, there is an immediate problem that the input can be "overrun" if I type fast or hold down a letter.

The other issue is that in the sample above I'm not checking if the number is a valid number at that position (example: you can currently enter a number higher than 59 for min or sec). I can do that by validating every number at every position but that seems to be a wrong approach.

Any help is appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source