Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 208
systempuntoout Avatar asked Apr 06 '11 07:04

systempuntoout


People also ask

How do you validate a value in JavaScript?

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");

How do you validate a date field?

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!


2 Answers

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);" />
like image 173
dominicbri7 Avatar answered Sep 16 '22 14:09

dominicbri7


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.

like image 26
TRT 1968 Avatar answered Sep 18 '22 14:09

TRT 1968