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

后端 未结 8 1036
灰色年华
灰色年华 2020-12-28 13:49

I have to build an HTML Form with an Input text field for Hours and Minutes.
Something like:

Name : [Foo]
Surname

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 14:14

    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;
      }

提交回复
热议问题