Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...