How to validate with Javascript an Input text with Hours and Minutes

<HTML>
<Head>
<script language="javascript">
function validateTime(obj)
{
    var timeValue = obj.value;
    if(timeValue == "" || timeValue.indexOf(":")<0)
    {
        alert("Invalid Time format");
        return false;
    }
    else
    {
        var sHours = timeValue.split(':')[0];
        var sMinutes = timeValue.split(':')[1];

        if(sHours == "" || isNaN(sHours) || parseInt(sHours)>23)
        {
            alert("Invalid Time format");
            return false;
        }
        else if(parseInt(sHours) == 0)
            sHours = "00";
        else if (sHours <10)
            sHours = "0"+sHours;

        if(sMinutes == "" || isNaN(sMinutes) || parseInt(sMinutes)>59)
        {
            alert("Invalid Time format");
            return false;
        }
        else if(parseInt(sMinutes) == 0)
            sMinutes = "00";
        else if (sMinutes <10)
            sMinutes = "0"+sMinutes;    

        obj.value = sHours + ":" + sMinutes;        
    }

    return true;    
}


</script>
</Head>
<Body>
<input type="text" onblur="validateTime(this)">
</Body>
</HTML>

Either with the following regular expression :

^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$

Or by hand, but I strongly suggest the RegExp :) A simple example :

function validateHhMm(inputField) {
    var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);

    if (isValid) {
      inputField.style.backgroundColor = '#bfa';
    } else {
      inputField.style.backgroundColor = '#fba';
    }

    return isValid;
  }
<input type="text" onchange="validateHhMm(this);" />

The RegExp from the first answer doesn't match the OP's query correctly.

^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$

Should be

^([0-1][0-9]|2[0-3]):([0-5][0-9])$

Matches 00-19 or 20-23 : 00-59

OP requested validation of HH:MM in the range 00:00 - 23:59

No seconds. 24:00 should not be valid. Double digits for input of hour and minute.


With moment.js the way is:

const time = '23:59'
moment(time, 'HH:mm', true).isValid()