Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

validation - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...