42

I have to build an HTML Form with an Input text field for Hours and Minutes.
Something like:

Name : [Foo]
Surname : [Bar]
Task : [Spam]
Hours Minutes : [00:15] <-- Input text.

How can I help/validate/force user to compile Hours and Minutes values in the only allowed HH:mm format using Javascript? *

Valid time range: from 00:00 to 23:59

* I can't use Jquery and of course I will double check the submitted value server side

systempuntoout
  • 71,966
  • 47
  • 171
  • 241
  • What about having 2 inputs one for hours one for minutes, and then on submit doing what u want with them. (validating then compiling them into whatever format you wish) – The_Butcher Apr 06 '11 at 07:50
  • Related question, http://stackoverflow.com/questions/1038754/time-input-field . Apparently "input mask" seems to be the key. – Juho Vepsäläinen Apr 06 '11 at 07:53

8 Answers8

87

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);" />
Swetank Poddar
  • 1,257
  • 9
  • 23
dominicbri7
  • 2,479
  • 4
  • 23
  • 33
32

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.

TRT 1968
  • 472
  • 4
  • 10
  • 2
    OP wanted leading 0 24-hour clock yet I needed a 24 hour clock with optional leading 0. I took your answer as a basis and came up with ^(|0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$ – Bryan Mar 01 '19 at 01:32
8
<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>
Mouadh
  • 289
  • 1
  • 3
  • 12
8

With moment.js the way is:

const time = '23:59'
moment(time, 'HH:mm', true).isValid()
Kkkk Kkkk
  • 261
  • 4
  • 4
3

You can use this function to check for time format:

function validateTime (time) {
  const timeReg = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/
  return time.match(timeReg)
}

If you want to have just hour and minute please replace timeReg with this:

const timeReg = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

And this one for the date format:

function validateDate (date) {
  try {
    new Date(date).toISOString()
    return true
  } catch (e) {
    return false
  }
}
Ali Hallaji
  • 3,712
  • 2
  • 29
  • 36
2

How about

function validTime(inputStr) {
    if (!inputStr || inputStr.length<1) {return false;}
    var time = inputStr.split(':');
    return time.length === 2 
           && parseInt(time[0],10)>=0 
           && parseInt(time[0],10)<=23 
           && parseInt(time[1],10)>=0 
           && parseInt(time[1],10)<=59;
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • For this string: "1rrrr2:23" it returns true. For some reason parseInt for "1rrrr2" is valid. – Programmer Apr 20 '15 at 10:25
  • Yes, `parseInt("1rrrr2",10)` results in `1`, because the input string begins with a value that can be converted to int. See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – KooiInc Apr 20 '15 at 12:13
1

You can use something like jQuery.maskedit

VeroLom
  • 3,856
  • 9
  • 34
  • 48
0

might not be the best but this works for me. i am returning false if there is no error in this case. checks for both format and values.

if (value.substr(2,1) === ':') {
    if (!value.match(/^\d\d:\d\d/)) {
        return "Invalid Format";
    }
    else if (parseInt(value.substr(0,2)) >= 24 || parseInt(value.substr(3,2)) >= 60)  {
        return "Invalid Format";
    }
    else {
        return false;
    }

}
else {
    return "Invalid Format";
}
Lomi Faith
  • 35
  • 1
  • 6