I have to build an HTML Form with an Input text field for Hours and Minutes.
Something like:
Name : [Foo]
Surname
With moment.js the way is:
const time = '23:59'
moment(time, 'HH:mm', true).isValid()
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.
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;
}
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";
}
<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);" />