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
If the number string is invalid, it will return NaN (Not a Number), something you can test for easily: var numStr = "ab123c"; var numNum = +numStr; if (isNaN(numNum)) alert("numNum is not a number");
The date in the date field has to be after today's date and not in the past. It also has to be within 30 days from today's date. So if today is 15/01/2013, then the form can only accept any date within 30 days after the 15/02/2013, so the 14/04/2007 plus 30 days!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With